如何从列表列表中制作平面列表 [英] How to make a flat list out of a list of lists
问题描述
有没有捷径可以从 Python 中的列表列表中创建一个简单的列表?
Is there a shortcut to make a simple list out of a list of lists in Python?
我可以在 for
循环中完成,但是有没有一些很酷的单行"?
I can do it in a for
loop, but is there some cool "one-liner"?
我用 functools.reduce()
试过了:
from functools import reduce
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
但我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
推荐答案
给定一个列表 t
,
flat_list = [item for sublist in t for item in sublist]
意思是:
flat_list = []
for sublist in t:
for item in sublist:
flat_list.append(item)
比目前发布的快捷方式更快.(t
是要展平的列表.)
is faster than the shortcuts posted so far. (t
is the list to flatten.)
这里是对应的函数:
def flatten(t):
return [item for sublist in t for item in sublist]
作为证据,您可以使用标准库中的 timeit
模块:
As evidence, you can use the timeit
module in the standard library:
$ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in t for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(t, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,t)'
1000 loops, best of 3: 1.1 msec per loop
说明:基于+
的快捷键(包括sum
中的隐含使用),必然是O(T**2)
当有 T 个子列表时——随着中间结果列表越来越长,每一步都会分配一个新的中间结果列表对象,并且必须复制前一个中间结果中的所有项(以及一些新的项)最后补充).因此,为简单起见且不失一般性,假设每个子列表都有 k 个项目:前 k 个项目来回复制 T-1 次,后 k 个项目 T-2 次,依此类推;总拷贝数是x从1到T排除x的总和的k倍,即k * (T**2)/2
.
Explanation: the shortcuts based on +
(including the implied use in sum
) are, of necessity, O(T**2)
when there are T sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have T sublists of k items each: the first k items are copied back and forth T-1 times, the second k items T-2 times, and so on; total number of copies is k times the sum of x for x from 1 to T excluded, i.e., k * (T**2)/2
.
列表推导式只生成一个列表,一次,并将每个项目(从其原始居住地到结果列表)复制一次.
The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.
这篇关于如何从列表列表中制作平面列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!