python - get list of tuples first index?

佐手、 提交于 2019-12-17 10:52:48

问题


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]

回答1:


use zip if you need both

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



回答2:


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



回答3:


>>> 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:

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



回答4:


You can try this too..

dict(my_list).keys()



回答5:


Try this.

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


来源:https://stackoverflow.com/questions/10735282/python-get-list-of-tuples-first-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!