Creating a Python list from a list of tuples

核能气质少年 提交于 2019-12-01 12:53:26

问题


If I have, for example, a list of tuples such as

a = [(1,2)] * 4

how would I create a list of the first element of each tuple? That is, [1, 1, 1, 1].


回答1:


Use a list comprehension:

>>> a = [(1,2)] * 4
>>> [t[0] for t in a]
[1, 1, 1, 1]

You can also unpack the tuple:

>>> [first for first,second in a]
[1, 1, 1, 1]

If you want to get fancy, combine map and operator.itemgetter. In python 3, you'll have to wrap the construct in list to get a list instead of an iterable:

>>> import operator
>>> map(operator.itemgetter(0), a)
<map object at 0x7f3971029290>
>>> list(map(operator.itemgetter(0), a))
[1, 1, 1, 1]



回答2:


Two alternatives to phihag's list comprehension:

[x for x, y in a]

from operator import itemgetter
map(itemgetter(0), a)



回答3:


There are several ways:

>>> a = [(1,2)] * 4

>>> # List comprehension
>>> [x for x, y in a]
[1, 1, 1, 1]

>>> # Map and lambda
>>> map(lambda t: t[0], a)
[1, 1, 1, 1]

>>> # Map and itemgetter
>>> import operator
>>> map(operator.itemgetter(0), a)
[1, 1, 1, 1]

The technique of using map fell out of favor when list comprehensions were introduced, but now it is making a comeback due to parallel map/reduce and multiprocessing techniques:

>>> # Multi-threading approach
>>> from multiprocessing.pool import ThreadPool as Pool
>>> Pool(2).map(operator.itemgetter(0), a)
[1, 1, 1, 1]

>>> # Multiple processes approach
>>> from multiprocessing import Pool
>>> def first(t):
        return t[0]
>>> Pool(2).map(first, a)
[1, 1, 1, 1]



回答4:


a = [(1,2)] * 4
first_els = [x[0] for x in a]



回答5:


Assuming you have a list of tuples:

lta = [(1,2), (2,3), (44,45), (37,38)]

access the first element of each tuple would involve subscripting with [0], and visiting each tuple to extract each first element would involve a a list comprehension, which can be assigned to a variable as shown below:

resultant_list = [element[0] for element in lta]
>>> resultant_list
[1, 2, 44, 37]



回答6:


I recently found out about Python's zip() function. Another way to do what I want to do here is:

list( zip( *a )[0] )

tup_list = zip( list1, list2 ) interleaves two lists into a list of 2-tuples, but zip( *tup_list ) does the opposite, resulting in a list of a tuple of list1 and a tuple of list2.



来源:https://stackoverflow.com/questions/11231186/creating-a-python-list-from-a-list-of-tuples

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