本文介绍了如何从列表列表中制作平面列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有捷径可以在Python的列表列表中创建一个简单的列表?

Is there a shortcut to make a simple list out of a list of lists in Python?

我可以在 for 循环中执行此操作,但是也许有一些很酷的单线"功能?我尝试了 functools.reduce()

I can do it in a for loop, but maybe there is some cool "one-liner"? I tried it with 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.)

以下是对应的功能:

flatten = lambda t: [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个项目的T个子列表:前k个项目来回复制T-1次,后k个项目T-2次,依此类推;等等.复制总数是k的x乘以x从1到T的x的总和,即 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.

这篇关于如何从列表列表中制作平面列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:28