How do I flatten a list of lists/nested lists?
本问题已经有最佳答案,请猛点这里访问。
我有这样的python代码:
1 2 3 4 | newlist =[[52, None, None], [129, None, None], [56, None, None], [111, None, None], [22, None, None], [33, None, None], [28, None, None], [52, None, None], [52, None, None], [52, None, None], [129, None, None], [56, None, None], [111, None, None], [22, None, None], [33, None, None], [28, None, None]] |
我要的是
1 2 3 4 | newlist =[52, None, None,129, None, None,56, None, None,111, None, None,22, None, None,33, None, None,28, None, None,52, None, None,52, None, None,52, None, None,129, None, None,56, None, None, 111, None, None,22, None, None,33, None, None,28, None, None] |
有什么办法可以解决吗?
你所要做的就是把名单拉平。根据Python的禅宗,你是在做正确的事情。从中引用
Flat is better than nested.
所以你可以用这样的列表理解
1 | newlist = [item for items in newlist for item in items] |
或者你可以这样使用EDOCX1的
1 2 | from itertools import chain newlist = list(chain(*newlist)) |
或者您可以使用
1 2 | from itertools import chain newlist = list(chain.from_iterable(newlist)) |
使用
1 | newlist = sum(newlist, []) |
使用
1 | newlist = reduce(lambda x,y: x+y, newlist) |
使用
1 2 | import operator newlist = reduce(operator.add, newlist) |
编辑:为了完整起见,还包括在用python从列表中创建一个简单列表中找到的答案。
我试着用python 2.7来计时,就像这样
1 2 3 4 5 6 7 | from timeit import timeit print(timeit("[item for items in newlist for item in items]","from __main__ import newlist")) print(timeit("sum(newlist, [])","from __main__ import newlist")) print(timeit("reduce(lambda x,y: x+y, newlist)","from __main__ import newlist")) print(timeit("reduce(add, newlist)","from __main__ import newlist; from operator import add")) print(timeit("list(chain(*newlist))","from __main__ import newlist; from itertools import chain")) print(timeit("list(chain.from_iterable(newlist))","from __main__ import newlist; from itertools import chain")) |
我机器上的输出
1 2 3 4 5 6 | 2.26074504852 2.45047688484 3.50180387497 2.56596302986 1.78825688362 1.61612296104 |
因此,最有效的方法是在python 2.7中使用
1 2 3 4 5 6 7 | from timeit import timeit print(timeit("[item for items in newlist for item in items]","from __main__ import newlist")) print(timeit("sum(newlist, [])","from __main__ import newlist")) print(timeit("reduce(lambda x,y: x+y, newlist)","from __main__ import newlist; from functools import reduce")) print(timeit("reduce(add, newlist)","from __main__ import newlist; from operator import add; from functools import reduce")) print(timeit("list(chain(*newlist))","from __main__ import newlist; from itertools import chain")) print(timeit("list(chain.from_iterable(newlist))","from __main__ import newlist; from itertools import chain")) |
我机器上的输出
1 2 3 4 5 6 | 2.26074504852 2.45047688484 3.50180387497 2.56596302986 1.78825688362 1.61612296104 |
因此,无论是python 2.7还是3.3,都可以使用
1 2 3 4 | temp = [] for small_list in newlist: temp += small_list newlist = temp |
应该这样做。
最简单的一个:
1 2 | newlist = sum(newlist, []) print newlist |
尝试:
1 | newlist = [j for i in newlist for j in i] |