繁体   English   中英

从元组列表创建Python列表

[英]Creating a Python list from a list of tuples

例如,如果我有一个元组列表,例如

a = [(1,2)] * 4

我将如何创建每个元组的第一个元素的列表? [1, 1, 1, 1]

使用列表理解

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

您还可以打开元组的包装:

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

如果您想花哨的话,请结合mapoperator.itemgetter 在python 3中,您必须将构造包装在list以获得一个列表,而不是一个可迭代的列表:

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

phihag列表理解的两种替代方法:

[x for x, y in a]

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

有几种方法:

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

引入列表理解后,使用地图的技术就不受欢迎了,但是现在由于并行地图/归约和多处理技术而卷土重来:

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

假设您有一个元组列表:

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

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

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

我最近发现了Python的zip()函数。 做我想在这里做的另一种方法是:

list( zip( *a )[0] )

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