简体   繁体   中英

Creating a Python list from a list of tuples

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] .

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]

Two alternatives to phihag's list comprehension:

[x for x, y in a]

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

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]
a = [(1,2)] * 4
first_els = [x[0] for x in a]

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 aa 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]

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM