简体   繁体   English

从元组列表创建Python列表

[英]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] . [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 . 如果您想花哨的话,请结合mapoperator.itemgetter In python 3, you'll have to wrap the construct in list to get a list instead of an iterable: 在python 3中,您必须将构造包装在list以获得一个列表,而不是一个可迭代的列表:

>>> 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: phihag列表理解的两种替代方法:

[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: 访问每个元组的第一个元素将涉及用[0]下标,并且访问每个元组以提取每个第一个元素将涉及一个列表理解,可以将其分配给一个变量,如下所示:

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

I recently found out about Python's zip() function. 我最近发现了Python的zip()函数。 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 . tup_list = zip( list1, list2 )两个列表交织为2个元组的列表,但是zip( *tup_list )却相反,从而得到list1元组和list2元组的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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