在Python中,如何展平嵌套列表?如何让Python在单个元素上迭代(一次)



如何使单个实例(如int或str(可迭代。也就是说,我如何使可能包含嵌套列表的列表变平。这很重要。考虑一下,列表(或函数返回(可以包含可迭代的,就像列表或生成器一样,但它也可以包含单个值。我必须处理它们。在下面的例子中,我有一个包含奇异元素和元素列表的列表。我只想把它们整理成一个简单的列表。我该怎么做?

org_l = [[1,2,3,4],[5],6,7,[8,9,0]]
new_l = [e1 for e in l for e1 in e]
Traceback (most recent call last):
File "C:UserskrisvPycharmProjectspythonProjectmain.py", line 101, in <module>
l = [e1 for e in l for e1 in e]
File "C:UserskrisvPycharmProjectspythonProjectmain.py", line 101, in <listcomp>
l = [e1 for e in l for e1 in e]
TypeError: 'int' object is not iterable

需要的是newl,它等于:[1,2,3,4,5,6,7,8,9,0]

我将回答我自己的问题:

def unroll(thing):
if isinstance(thing, typing.Iterable) and not isinstance(thing, str):
for e in thing:
yield from unroll(e)
else:
yield thing
l = [[1,2,[3,'c'],4],[5],6,7,7.5,[8,9,9.5,0]]
flat_list = [e for e in unroll(l)]
print(flat_list)
>>>
[1, 2, 3, 'c', 4, 5, 6, 7, 7.5, 8, 9, 9.5, 0]

最新更新