如何提取嵌套列表?

时间:2011-11-30 14:54:37

标签: python list

  

重复:

     

假设我有一个包含嵌套列表的列表:

[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]

将它转换为单个列表的最佳方法是什么

["a", "b", "c", "d", "e"....]

3 个答案:

答案 0 :(得分:23)

使用itertools.chain

from itertools import chain

list(chain.from_iterable(list_of_lists))

答案 1 :(得分:11)

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']

答案 2 :(得分:2)

使用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 方式来实现结果。

相关问题