You could just do:
print(friends[1])
That would give the second element, it will output:
Mark
If you want to use a loop, try:
for i, v in enumerate(friends):
if i == 1:
print(v)
Output:
Mark
Python indexing starts from 0, so the second element's index would be 1.
The for loop I did iterates through the list, but the iterator i is the index of every element, and v is the value, so it check if i (the index) is 1, if so, it prints v.
You could just do:
print(friends[1])
That would give the second element, it will output:
Mark
If you want to use a loop, try:
for i, v in enumerate(friends):
if i == 1:
print(v)
Output:
Mark
Python indexing starts from 0, so the second element's index would be 1.
The for loop I did iterates through the list, but the iterator i is the index of every element, and v is the value, so it check if i (the index) is 1, if so, it prints v.
You can also use a counter for such problems. I've set it to 0 and for every iteration, it gets incremented by 1. So, to access the 2nd element cnt would be 2. You can add an if statement and print only Mark
friends = ["John", "Mark", "James"]
cnt=0
for friend in friends:
cnt+=1
if cnt==2:
print(friend)
You can try list indexing:
data = [[6.0, 0.5], [6.1, 1.0], [6.2, 1.5], [6.3, 2.0], [6.4, 2.5], [6.5, 3.0], [6.6, 3.5], [6.7, 4.0], [6.8, 4.5]]
d1 = [item[0] for item in data]
print d1
d2 = [item[1] for item in data]
print d2
output :
[6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8]
[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
zip() will provide the required output.
xy = [[6.0, 0.5], [6.1, 1.0], [6.2, 1.5], [6.3, 2.0], [6.4, 2.5], [6.5, 3.0], [6.6, 3.5], [6.7, 4.0], [6.8, 4.5]]
x,y = zip(*xy)
print(x)
print(y)
Output:
(6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8)
(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5)
zip() aggregates the elements from all the iterable. zip(x,y) would provide the list you currently have. zip() with * can be used to unzip a list.
Also, there is no need to convert the tuples to list since pyplot.plot() takes an array-like parameter.
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()

In a Python list, how can I print the 1st and 2nd elements on a line, the 3rd and 4th on the next line, and so forth? - Stack Overflow
Python print nth element from list of lists - Stack Overflow
How do I access the 2nd item in a list?
python - Printing specific items out of a list - Stack Overflow
Printing 2 values on a list is as simple as creating a for loop that skips over every other value. When you create a for loop, you can use range(start,stop,interval) to accomplish this. Then you can just fill in the two print statements using the for loop
I hope that this will work for you:
for x in range(0,len(listtest),2):
print (listtest[x], listtest[x+1])
replace testlist with your list's name
Firstly, you shouldn't be using list as a variable name, as its already a built-in function.
Secondly you can get every odd indexed item by slicing [::2], and every even indexed item with [1::2], which is show below:
>>> my_list = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
>>> print(my_list[::2])
['first', 'third', 'fifth']
>>> print(my_list[1::2])
['second', 'fourth', 'sixth']
Then you can just zip() the lists together and print them:
my_list = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
for x, y in zip(my_list[::2], my_list[1::2]):
print(x, y)
Which outputs:
first second
third fourth
fifth sixth
Many way to do this. Here's a simple list way, without an explicit for loop.
tt = [[50.954818803035948, 55.49664787231189, 8007927.0, 0.0], [50.630482185654436, 55.133473852776916, 8547795.0, 0.0], [51.32738085400576, 55.118344981379266, 6600841.0, 0.0], [49.425931642638567, 55.312890225131163, 7400096.0, 0.0], [48.593467836476407, 55.073137270550006, 6001334.0, 0.0]]
print [x[2] for x in tt]
> [8007927.0, 8547795.0, 6600841.0, 7400096.0, 6001334.0]
And making is safe for potentially shorted lists
print [x[2] for x in tt if len(tt) > 3]
More sophisticated output (python 2.7), prints values as newline (\n) seperated
print '\n'.join([str(x[2]) for x in tt])
> 8007927.0
> 8547795.0
> 6600841.0
> 7400096.0
> 6001334.0
Maybe you try a map function In python 3:
list(map(lambda l: l[2], z))
In python 2:
map(lambda l: l[2], z)
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
Then just iterate over the sublist:
>>> for item in li[2:]:
... print item
...
3
4
You should do:
for i in [2, 3]:
print(li[i])
By range(n), you are getting [0, 1, 2, ..., n-1]
By range(m, n), you are getting [m, m+1, ..., n-1]
That is why you use range, getting a list of indices.
It is more recommended to use slicing like other fellows showed.
I’ve been trying to figure out how to find the index number of the second occurrence of a list of numbers and then print from 0 index to the second occurrence number’s index from that list. I’ve been breaking me head for like two days with trial and error. I did the first occurrence and it works fine. Please help. Thank you!
data = [('name1', 'alan'), ('name2', 'bob'), ('name3', 'alice'), ('name4', 'john')]So how do I get only second column for above list so output would be below
alan
bob
alice
john
You missed the brackets. Try this:
p = [x[1] for x in list_of_numbers]
To print the values, you could use
print(', '.join([str(x) for x in p]))
You also need to change the way you load the data from the file
Full Code:
def parse(raw):
data = []
for line in raw.split("\n"):
line = line.strip()
# --> "('5', 2.5, 5200)"
if line.startswith("(") and line.endswith(")"):
d = line[line.index("(")+1 : line.index(")", -1)]
# --> "'5', 2.5, 5200"
d = d.split(",")
data.append([])
for i in d:
i = i.strip()
try:
i = float(i)
except:
pass
data[-1].append(i)
return data
raw = open("list_of_numbers.txt").read()
list_of_numbers = parse(raw)
p = [x[1] for x in list_of_numbers]
# --> [2.5, 3.2, 5.4, 8.7]
print(', '.join([str(x) for x in p]))
# ---> 2.5, 3.2, 5.4, 8.7
I suggest using pickle. Storing and loading your data is easy as:
import pickle
data = ...
# store
file = open('data.txt', 'w')
pickle.dump(data, file)
file.close()
# load
file = open('data.txt', 'r')
data = pickle.load(file)
file.close()
Another option is to use numpy.ndarray.
import numpy as np
list_of_numbers = [
('5', 2.5, 5200),
('6', 3.2, 5236),
('8', 5.4, 5287),
]
list_of_numbers = np.array(list_of_numbers)
p = list_of_numbers[:,1]
print(p)
# outputs: ['2.5' '3.2' '5.4']
In addition, since you're reading data from a text file, your first list should contain only str. (I really don’t understand how you get mixed strings and numbers using the method you describe in your question.) To fix that, you can either:
- use
numpy.loadtxt, - convert to
floatwhen switching to a ndarray: `np.array(list_of_numbers, dtype=float).
Finally, I strongly suggest that you learn about slices in Python.
You're getting this error because you try to access the second element of an array that contains only 1 string. In this case you want to check the length of the array
for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
for test in words:
if len(words) > 1:
print(words)
else: # this else is not necessary
continue
Edit: If you want to print each sentences containing at least one ';' only once, you don't actually have to use a for loop. One concise way to get the desired output would be this:
for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)
As far as I understand from your question you only trying to print the words list which has more than one element.
One simple way to do it is:
for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
# first = words[0]
for test in words:
if len(words) > 1:
print(words)
Here you are just checking if the length of the words is greater than 1 and printing if that is the case
EDIT: I think the for loop is unnecessary. All you want is to print lists of words greater than length 1. So for that purpose:
for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)
Here you are just splitting the sentences on ; and then checking after splitting if the length of the list (named words) is greater than 1; if so you are printing the list named words.
EDIT2:
As S3DEV had pointed out that you are opening a file inside for keyword which won't close your file automatically once you are out of for loop. As a result the file pointer remains open until the program stopped completely and it might cause weird issues. The best practice is to use with keyword. the with keyword automatically opens the file nad closes it once the block execution is complete, so you won't face any odd issues. form keeping a file pointer open.
with open("testing.txt", "r") as f: # this line open file as f in read-only format
for line in f:
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)