繁体   English   中英

在python 3中展平多维数组

[英]Flatten multi dimensional array in python 3

我有一个数字列表:testList = [1,[1],[12],2,3]

我希望它成为:flatList = [1,1,12,2,3]

使用典型的列表理解(如下所示)不起作用。

flatList = [val for sublist in testList for val in sublist]
TypeError: 'int' object is not iterable

我怀疑这是因为未嵌套的项目被视为可迭代的子列表,所以我尝试了这个:

flatList = [val if isinstance(sublist, int) == False else val for sublist in testlist for val in sublist]

但我不清楚语法,或者是否有更好的方法来做到这一点。 尝试从else子句中删除val意味着val未定义。 它仍然给我相同的TypeError。

下面的代码对我有用,但我有兴趣看看它是否可以用列表理解方式完成,以及人们对此的看法。

for sublist in testlist:
    if type(sublist) == int:
        flat.append(sublist)
    else:
        for val in sublist:
            flat.append(val)
print(flat)

>>>[1, 1, 12, 2, 3]

如果子列表总是只包含一个项目

flatList = [item[0] if isinstance(item, list) else item for item in testList]

由于您使用的是Python 3,因此可以通过递归函数利用yield from 它已在Python 3.3中引入。

作为奖励,您可以展平任意嵌套列表,元组,集合或范围:

test_list = [1, [1], [12, 'test', set([3, 4, 5])], 2, 3, ('hello', 'world'), [range(3)]]

def flatten(something):
    if isinstance(something, (list, tuple, set, range)):
        for sub in something:
            yield from flatten(sub)
    else:
        yield something


print(list(flatten(test_list)))
# [1, 1, 12, 'test', 3, 4, 5, 2, 3, 'hello', 'world', 0, 1, 2]
print(list(flatten('Not a list')))
# ['Not a list']
print(list(flatten(range(10))))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这是调试行的另一个例子:

def flatten(something, level=0):
    print("%sCalling flatten with %r" % ('  ' * level, something))
    if isinstance(something, (list, tuple, set, range)):
        for sub in something:
            yield from flatten(sub, level+1)
    else:
        yield something

list(flatten([1, [2, 3], 4]))
#Calling flatten with [1, [2, 3], 4]
#  Calling flatten with 1
#  Calling flatten with [2, 3]
#    Calling flatten with 2
#    Calling flatten with 3
#  Calling flatten with 4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM