Python提取多级嵌套列表

标签 python python-3.x list nested-lists

有这个列表

l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]

我想要一个提取所有嵌套列表并返回的函数

l = [['a', 'b', 'c', 'd'],["d","d"],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]

类似于展平,但保留每个嵌套列表的列表结构。 这是我最接近的一次,我觉得有一种方法可以实现我的目标,而无需使用额外的结构来过滤重复项。此外,在字符串和列表级别顺序很重要

def get_all_nested_list(l,returned_list):
    nested_list = l
    while isinstance(nested_list, list):
        for elem in nested_list:
            get_all_nested_list(elem,returned_list)
        if isinstance(nested_list[0], str):
            returned_list.append(nested_list)
        nested_list = nested_list[0]


if __name__ == '__main__':
    l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
    l2 = []
    get_all_nested_list(l,l2)
    print(l2)

通过使用 itertools 或建议使用 Yield 的实际正确方法而不是传递另一个列表作为参数来实现上述目的的任何其他方法都非常受欢迎。

最佳答案

你可以尝试递归函数

my_nested_list = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]

def flatten(nested_list):
    for item in nested_list:
        if not isinstance(item[0],list):
            yield item
        else:
            yield from flatten(item)

flat_list = [item for item in flatten(my_nested_list)]
print(flat_list)

关于Python提取多级嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60348623/

相关文章:

python - 如何从 mqtt 主题获取通配符值?

python - 优化 django 查询以避免使用详细 View 和覆盖 get_context_data 时出现重复

python - 简单的按钮点击连接到Python函数

Python向list添加多个列表

PHP 数组中的有序列表

python - 将 Flask 应用部署为 Windows 服务

python - 为大量属性实现 setter 和 getter 的简洁方法?

java - 使用java将单链表转换为双向链表

python - 如何使 threading.Thread start() 调用 run() 以外的方法

python - 使用 Python 中的 ImageDraw 在图像中写入文本。如何确定哪种字体适合哪种语言和脚本?