Sorry in advance, but I'm new to Python. I have a list of tuples
, and I was wondering how I can reference, say, the first element of each tuple
within the list. I would think i开发者_StackOverflow社区t's something like
for i in number_of_tuples :
first_element = myList[i[0]]
you know, [list_element[tuple_element]]
? However, this doesn't appear to be the right approach. Any help would be greatly appreciated.
Thanks,
Turner
All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]]
you are telling Python that i
is a tuple and you want the value or the first element of tuple i
as the index for myList.
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
This is a quick rudimentary example that I came up with:
info = [ ( 1, 2), (3, 4), (5, 6) ]
info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6
You can get a list of the first element in each tuple using a list comprehension:
>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']
The code
my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
prints
(1, 2)
(3, 4)
(5, 6)
The loop iterates over my_list
, and assigns the elements of my_list
to t
one after the other. The elements of my_list
happen to be tuples, so t
will always be a tuple. To access the first element of the tuple t
, use t[0]
:
for t in my_list:
print t[0]
To access the first element of the tuple at the given index i
in the list, you can use
print my_list[i][0]
You also can use itemgetter operator:
from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)
Rather than:
first_element = myList[i[0]]
You probably want:
first_element = myList[i][0]
So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy
provides.
Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]])
, you can use arr[:, 0]
to get a new array of all the first elements in each "tuple".
Here's a quick example:
termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))
result = [x[1] for x in termList if x[0] == 'term3']
print(result)
精彩评论