提前道歉,我是Python新手。 我有一个元组(tuples)列表,我想知道如何引用列表中每个元组的第一个元素。 我认为应该像这样:
for i in number_of_tuples :
first_element = myList[i[0]]
你知道 [列表元素[元组元素]]
吗?但是,这似乎不是正确的方法。非常感谢任何帮助。
谢谢,
特纳
myList[i[0]]
时,你告诉Python i
是一个元组,并且你想要元组i
的第一个元素的值作为 myList 的索引。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
>>> 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']
for x in my_tuples
...?在Python编程中,这段代码表示使用for循环遍历名为my_tuples的元组。 - Matt Ballmy_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
打印
(1, 2)
(3, 4)
(5, 6)
这个循环遍历了my_list
,并将my_list
的元素一个接一个地赋值给t
。由于my_list
的元素恰好是元组,所以t
始终是一个元组。要访问元组t
的第一个元素,请使用t[0]
:
for t in my_list:
print t[0]
[i] [0]
。print my_list[i][0]
print()
,其他答案内容保持不变。 - Sven Marnach您还可以使用itemgetter运算符:
from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)
不是:
first_element = myList[i[0]]
您可能需要:
first_element = myList[i][0]
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)
numpy
提供的。arr = numpy.array([[1, 2], [3, 4], [5, 6]])
,你可以使用 arr[:, 0]
来获取所有“元组”中第一个元素的新数组。通过我的方法,您无需导入任何模块,它更符合Python的风格,因为它使用Python的本地特性:
list_of_tuples = [('a1', 'b1','c1'), ('a2', 'b2','c2'), ('a3', 'b3','c3')]
print(list(map(lambda x: x[0], list_of_tuples)))
>> ['a1', 'a2', 'a3']
print(list(map(lambda x: x[2], list_of_tuples)))
>> ['c1', 'c2', 'c3']