什么是删除list-in-list层次结构的最pythonic方法?Python - 删除List-in-List层次结构?
也就是说,从
A=[[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
到
B=[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
什么是删除list-in-list层次结构的最pythonic方法?Python - 删除List-in-List层次结构?
也就是说,从
A=[[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
到
B=[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
“最Python的” 可争论不休。我更喜欢嵌套的列表理解来拼合嵌套列表。
B = [element for sublist in A for element in sublist]
当它归结到它,使用,因为你可能谁最经常与你的代码交互的人什么是最可读性你。
import operator
reduce(operator.add, A)
或
reduce(lambda x,y:x+y, A)
它更Python使用chain.from_iterable解开嵌套列表
>>> from itertools import chain
>>> list(chain.from_iterable(A))
[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
import itertools
a = [[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
list(itertools.chain(*a))
退房的itertools module。洛特的好东西。
太棒了,它的工作原理!但你介意解释一下吗?这个 –
背后的基本原理是什么?你可以看看[reduce](http://docs.python.org/2/library/functions.html#reduce)。在这种情况下,'operator.add'表示lambda x,y:x + y – waitingkuo
**注意**,reduce已被弃用并在Python 3.x中删除。然后你需要使用[functools.reduce](http://docs.python.org/2/library/functools.html#functools.reduce) – Abhijit