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

标签 python list

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

相关文章:

c# - 将 IList 转换为列表

python - 通过子字符串检查列表中的元素

python - 如何拆分具有多个选项的 Pandas 系列?

python - 如何限制可以传递给方法参数的允许值(使用类型提示允许静态代码分析)

python - 以列表理解方式更新对象属性

java - ArrayList 中的元素如何工作?

python - getthreshold() 除了垃圾回收之外的用途

python - 如何在python2.7中安装python black工具

python - 拆分 Pandas 列并将最后一个元素添加到新列

c++ - 在 C++ 中遍历自定义结构列表的小问题