我遵循了使用以下代码在 python ( Flatten (an irregular) list of lists ) 中展平不规则列表列表的最佳解决方案:
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
L = [[[1, 2, 3], [4, 5]], 6]
L=flatten(L)
print L
得到如下输出:
“生成器对象在 0x100494460 变平”
我不确定我需要导入哪些包或我需要更改语法才能让它为我工作。
最佳答案
您可以直接迭代生成器对象:
for x in L:
print x
或者如果你真的需要一个列表,你可以从中制作一个:
list(L)
关于python - 使用 collections.Iterable 在 python 中展平不规则列表时,列表不会作为最终对象返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737499/