Skip to main content
 首页 » 编程设计

python之使用 collections.Iterable 在 python 中展平不规则列表时,列表不会作为最终对象返回

2025年05月04日11mate10pro

我遵循了使用以下代码在 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)