如何从列表列表中制作平面列表? [英] How to make a flat list out of list of lists?

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

问题描述

我想知道是否有捷径可以在Python的列表列表之外制作一个简单的列表.

I wonder whether there is a shortcut to make a simple list out of list of lists in Python.

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

I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with reduce(), but I get an error.

代码

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'

推荐答案

给出列表列表l

flat_list = [item for sublist in l for item in sublist]

这意味着:

flat_list = []
for sublist in l:
    for item in sublist:
        flat_list.append(item)

比到目前为止发布的快捷方式快. (l是要展平的列表.)

is faster than the shortcuts posted so far. (l is the list to flatten.)

以下是对应的功能:

flatten = lambda l: [item for sublist in l for item in sublist]

作为证据,您可以使用标准库中的timeit模块:

As evidence, you can use the timeit module in the standard library:

$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop

说明:当有L个子列表时,基于+的快捷方式(包括sum中的隐含用法)必然是O(L**2)-由于中间结果列表会越来越长,因此在每个步骤a将分配新的中间结果列表对象,并且必须复制以前的中间结果中的所有项目(以及最后添加的一些新项目).因此,为简单起见,而又不失去一般性,请说您有I个项目的L个子列表:第一个I项目来回复制L-1次,第二个I项目L-2次,依此类推;等等.复制总数是I乘以x的x的总和(从1到L),即I * (L**2)/2.

Explanation: the shortcuts based on + (including the implied use in sum) are, of necessity, O(L**2) when there are L 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 L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., I * (L**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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆