如何在Python中将嵌套列表转换为一维列表?

com*_*ski 10 python nested-lists python-2.7

我尝试了一切(据我所知)分裂数组并将它们连接在一起甚至使用itertools:

import itertools

def oneDArray(x):
    return list(itertools.chain(*x))
Run Code Online (Sandbox Code Playgroud)

我想要的结果:

一个) print oneDArray([1,[2,2,2],4]) == [1,2,2,2,4]

奇怪的是,它适用于

b) print oneDArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

问题1)我如何以我想要的方式获得工作(任何提示?)

问题2)为什么以上代码适用于b部分而不是a部分?

Ewa*_*wan 11

如果您正在使用,python < 3那么您可以执行以下操作:

from compiler.ast import flatten
list = [1,[2,2,2],4]
print flatten(list)
Run Code Online (Sandbox Code Playgroud)

python 3.0中的手册等价物(取自这个答案):

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, str):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

 print(flatten(["junk",["nested stuff"],[],[[]]]))  
Run Code Online (Sandbox Code Playgroud)

你甚至可以在列表理解中做同样的事情:

list = [1,[2,2,2],4]
l = [item for sublist in list for item in sublist]
Run Code Online (Sandbox Code Playgroud)

这相当于:

l = [[1], [2], [3], [4], [5]]
result = []
for sublist in l:
    for item in sublist:
        result.append(item)

print(result)
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 10

您需要递归循环遍历列表并检查项是否可迭代(字符串也可迭代,但跳过它们)或不.

itertools.chain不会为工作,[1,[2,2,2],4]因为它需要所有它的项目,以可迭代的,但14(整数)不迭代.这就是为什么它适用于第二个,因为它是一个列表列表.

>>> from collections import Iterable
def flatten(lis):
     for item in lis:
         if isinstance(item, Iterable) and not isinstance(item, basestring):
             for x in flatten(item):
                 yield x
         else:        
             yield item

>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

适用于任何级别的嵌套:

>>> a = [1,[2,2,[2]],4]
>>> list(flatten(a))
[1, 2, 2, 2, 4]
Run Code Online (Sandbox Code Playgroud)

与其他解决方案不同,这也适用于字符串:

>>> lis = [1,[2,2,2],"456"]
>>> list(flatten(lis))
[1, 2, 2, 2, '456']
Run Code Online (Sandbox Code Playgroud)

  • 如果使用 python 3,请将“basestring”替换为“str”。 (6认同)

小智 7

要从 python 中的嵌套列表制作单个列表,我们可以简单地执行以下操作:

from functools import reduce

some_list = [[14], [215, 383, 87], [298], [374], [2,3,4,5,6,7]]
single_list = reduce(lambda x,y: x+y, some_list)
print(single_list)
Run Code Online (Sandbox Code Playgroud)

输出: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]


Brn*_*ndn 6

from nltk import flatten

example_list = [1, [2, 3], 3]
flattened_list = flatten(example_list)
print(flattened_list)

Run Code Online (Sandbox Code Playgroud)

输出:[1,2,3,3]