且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-18 19:15:08

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

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

>>>从集合导入可迭代def展平(lis):对于 lis 中的项目:如果 isinstance(item, Iterable) 而不是 isinstance(item, str):对于展平(项目)中的 x:产量 x别的:产量项目>>>lis = [1,[2,2,2],4]>>>列表(展平(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]

适用于任何级别的嵌套:

>>>a = [1,[2,2,[2]],4]>>>列表(展平(a))[1, 2, 2, 2, 4]

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

>>>lis = [1,[2,2,2],456"]>>>列表(展平(lis))[1, 2, 2, 2, '456']

I tried everything (in my knowledge) from splitting the array and joining them up together and even using itertools:

import itertools

def oneDArray(x):
    return list(itertools.chain(*x))

The result I want:

a) print oneDArray([1,[2,2,2],4]) == [1,2,2,2,4]

Strangely, it works for

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

Question 1) How do I get part a to work the way I want (any hints?)

Question 2) Why does the following code above work for part b and not part a??

You need to recursively loop over the list and check if an item is iterable(strings are iterable too, but skip them) or not.

itertools.chain will not work for [1,[2,2,2],4] because it requires all of it's items to be iterable, but 1 and 4 (integers) are not iterable. That's why it worked for the second one because it's a list of lists.

>>> from collections import Iterable
def flatten(lis):
     for item in lis:
         if isinstance(item, Iterable) and not isinstance(item, str):
             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]

Works for any level of nesting:

>>> a = [1,[2,2,[2]],4]
>>> list(flatten(a))
[1, 2, 2, 2, 4]

Unlike other solutions, this will work for strings as well:

>>> lis = [1,[2,2,2],"456"]
>>> list(flatten(lis))
[1, 2, 2, 2, '456']