我有以下列表:
j = [
[(1, 100), (2, 80), (3, 40)],
[(2, 80), (1, 30), (4, 50), (3, 60)],
[(1, 40), (2, 70), (4, 30)]
]
如何打印每个第一个元素:
[1, 2 ,3]
[2, 1, 4, 3]
[1, 2, 4]
I tried with
for i in j:
print(i[0])
谢谢!
使用zip
和列表推导式:
[next(zip(*i)) for i in j]
[(1, 2, 3), (2, 1, 4, 3), (1, 2, 4)]
或者使用嵌套循环:
[[v[0] for v in i] for i in j]
[[1, 2, 3], [2, 1, 4, 3], [1, 2, 4]]
试试这个:
for i in j:
print([v[0] for v in i])
可以对每个列表使用python的列表推导式i:
for i in j:
print([x for x,y in i])
如果你以前没有使用过列表推导式,这意味着对于列表i(在本例中是一个元组(x,y))中的每个元素,使用x的值来创建这个新列表。
最难看、最不像python的形式,但最容易理解:
list_of_tuples = [[(1, 100), (2, 80), (3, 40)],
[(2, 80), (1, 30), (4, 50), (3, 60)],
[(1, 40), (2, 70), (4, 30)]]
for tuple_ in list_of_tuples : # iterating over the list items, i.e. the tuples
storage_list=[] # creating an empty list for storage of items we want to print
for item in tuple_: # iterating over the tuple items
storage_list.append(item[0]) # storing the first item of each tuple in the created list
print(storage_list)
输出:
[1, 2, 3]
[2, 1, 4, 3]
[1, 2, 4]