python - 获取元组列表的第一个索引?

时间:2023-01-15 20:27:00

What's the most compact way to return the following:

返回以下内容的最简洁方法是什么:

Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements.

给定一个元组列表,返回一个由元组组成的列表(或者第二个,无关紧要)。

For:

[(1,'one'),(2,'two'),(3,'three')]

returned list would be

返回的列表将是

[1,2,3]

5 个解决方案

#1


40  

use zip if you need both

如果你需要两个,请使用zip

>>> r=(1,'one'),(2,'two'),(3,'three')
>>> zip(*r)
[(1, 2, 3), ('one', 'two', 'three')]

#2


32  

>>> tl = [(1,'one'),(2,'two'),(3,'three')]
>>> [item[0] for item in tl]
[1, 2, 3]

#3


10  

>>> mylist = [(1,'one'),(2,'two'),(3,'three')]
>>> [j for i,j in mylist]
['one', 'two', 'three']
>>> [i for i,j in mylist]
[1, 2, 3]

This is using a list comprehension (have a look at this link). So it iterates through the elements in mylist, setting i and j to the two elements in the tuple, in turn. It is effectively equivalent to:

这是使用列表理解(看看这个链接)。因此,它遍历mylist中的元素,依次将i和j设置为元组中的两个元素。它实际上相当于:

>>> newlist = []
>>> for i, j in mylist:
...     newlist.append(i)
... 
>>> newlist
[1, 2, 3]

#4


0  

You can try this too..

你也可以试试这个..

dict(my_list).keys()

#5


0  

Try this.

>>> list(map(lambda x: x[0], my_list))

#1


40  

use zip if you need both

如果你需要两个,请使用zip

>>> r=(1,'one'),(2,'two'),(3,'three')
>>> zip(*r)
[(1, 2, 3), ('one', 'two', 'three')]

#2


32  

>>> tl = [(1,'one'),(2,'two'),(3,'three')]
>>> [item[0] for item in tl]
[1, 2, 3]

#3


10  

>>> mylist = [(1,'one'),(2,'two'),(3,'three')]
>>> [j for i,j in mylist]
['one', 'two', 'three']
>>> [i for i,j in mylist]
[1, 2, 3]

This is using a list comprehension (have a look at this link). So it iterates through the elements in mylist, setting i and j to the two elements in the tuple, in turn. It is effectively equivalent to:

这是使用列表理解(看看这个链接)。因此,它遍历mylist中的元素,依次将i和j设置为元组中的两个元素。它实际上相当于:

>>> newlist = []
>>> for i, j in mylist:
...     newlist.append(i)
... 
>>> newlist
[1, 2, 3]

#4


0  

You can try this too..

你也可以试试这个..

dict(my_list).keys()

#5


0  

Try this.

>>> list(map(lambda x: x[0], my_list))