如何从列表列表中制作一个平面列表

我想知道是否有一条快捷方式可以在Python列表中列出一个简单的列表。


我可以for循环播放,但也许有一些很酷的“单行”?我用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'


天涯尽头无女友
浏览 704回答 3
3回答

慕标琳琳

给出列表清单l,flat_list = [item for sublist in l for item in sublist]意思是:flat_list = []for sublist in l:&nbsp; &nbsp; for item in sublist:&nbsp; &nbsp; &nbsp; &nbsp; flat_list.append(item)比目前发布的快捷方式快。(l是要压扁的列表。)这是相应的功能:flatten = lambda l: [item for sublist in l for item in sublist]作为证据,您可以使用timeit标准库中的模块:$ 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)- 当中间结果列表持续变长时,在每个步骤分配新的中间结果列表对象,以及所有项目必须复制之前的中间结果(以及最后添加的一些新结果)。因此,为了简单而没有实际失去一般性,请说每个项目都有L个子列表:第一个I项目来回复制L-1次,第二个I项目L-2次,依此类推; 总拷贝数是I乘以x的总和,从1到L排除,即I * (L**2)/2。列表理解只生成一个列表一次,并将每个项目(从其原始居住地点到结果列表)复制一次。

慕工程0101907

你可以使用itertools.chain():>>>&nbsp;import&nbsp;itertools>>>&nbsp;list2d&nbsp;=&nbsp;[[1,2,3],[4,5,6],&nbsp;[7],&nbsp;[8,9]]>>>&nbsp;merged&nbsp;=&nbsp;list(itertools.chain(*list2d))或者,在Python> = 2.6,使用itertools.chain.from_iterable()不需要解压缩列表:>>>&nbsp;import&nbsp;itertools>>>&nbsp;list2d&nbsp;=&nbsp;[[1,2,3],[4,5,6],&nbsp;[7],&nbsp;[8,9]]>>>&nbsp;merged&nbsp;=&nbsp;list(itertools.chain.from_iterable(list2d))这种方法可以说更具可读性,[item for sublist in l for item in sublist]而且看起来更快:这种方法可以说更具可读性,[item for sublist in l for item in sublist]而且看起来更快:[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'10000 loops, best of 3: 24.2 usec per loop[me@home]$ 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: 45.2 usec per loop[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'1000 loops, best of 3: 488 usec per loop[me@home]$ 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: 522 usec per loop[me@home]$ python --versionPython 2.7.3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python