题目

我想知道Python中是否有什么简单的方法可以展开嵌套列表。

我可以用循环实现,但是有没有更酷的一行实现的方法,我尝试了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 "", line 1, in >

File "", line 1, in

AttributeError: 'NoneType' object has no attribute 'extend'

回答一

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

等价于:

for sublist in l:

for item in sublist:

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

回答二

>>> import itertools

>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]

>>> merged = list(itertools.chain(*list2d))

>>> import itertools

>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]

>>> merged = list(itertools.chain.from_iterable(list2d))

这种方法比[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 --version

Python 2.7.3

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐