重复问题:
假设我有一个包含嵌套列表的列表:
[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]
如何将它转换为单个列表?
["a", "b", "c", "d", "e"....]
重复问题:
假设我有一个包含嵌套列表的列表:
[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]
如何将它转换为单个列表?
["a", "b", "c", "d", "e"....]
from itertools import chain
list(chain.from_iterable(list_of_lists))
在itertools
文档中有一个明显的例子(参见http://docs.python.org/library/itertools.html#recipes查找flatten()
),但它很简单:
>>> from itertools import chain
>>> list(chain(*x))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
或者,可以在一个列表理解式中轻松完成:
>>> x=[["a","b","c"], ["d","e","f"], ["g","h","i","j"]]
>>> [j for i in x for j in i]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
或者通过reduce()
函数:
>>> from operator import add
>>> reduce(add, x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
list.__add__
也可用,无需从operator导入add。 - mh-firouzjah使用 itertools.chain
的替代方案是:
>>> li = [["a","b","c"], ["d","e","f"], ["g","h","i","j"]]
>>> chained = []
>>> while li:
... chained.extend(li.pop(0))
...
>>> chained
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
编辑:上面的例子会在构建新列表时消耗原始列表,因此如果您正在操作非常大的列表并希望最小化内存使用,则应该是一个优势。如果不是这种情况,我会考虑使用itertools.chain
更加“Pythonic”的方法来实现结果。
chain
或类似的解决方案具有更高的时间复杂度,因为pop(0)
是O(n) -- 请参见Python Wiki Time Complexity页面中“list section”的“delete item”条目。如果您想使用extend
并使整个过程成为线性时间,则只需for sublist in li: chained.extend(li)
-- 在Python中没有办法从list
中以线性时间完成它,而不需要额外的存储空间(我假设这就是您想避免的)。 - agfres = reduce(list.__add__, listofitems)
是安全的,不会出现你遇到的错误。 - mh-firouzjah
[["a", "d", "g"], ["a", "d", "h"], ["a", "d", "i"], ...]
这样的列表,这完全不是这里想要的。 - agf