rank vote view answer url
23 2203 1237032 36 url

在嵌套列表中获取 flat list

我好奇如何可以 flat 一个嵌套列表.

我可以用 for 循环来做, 但是有没有更好的方法?我试着用 reduce , 但是失败了

Code

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)

Error message

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
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)

这个是完整的写法:

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

可以用 timeit module 来验证效率:

$ 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
Copyright © taizilongxu 2018 all right reserved,powered by Gitbook该文件修订时间: 2018-10-17 17:33:54

results matching ""

    No results matching ""