如何从嵌套列表中提取所有子列表?

问题描述 投票:1回答:2

我有一个嵌套列表。例如:

['a', ['b', 'c', ['e', 'd']]]

我想获得一个列表,其中包含该列表和所有子列表分别作为元素。因此,预期结果是:

[['a', ['b', 'c', ['e', 'd']]], ['b', 'c', ['e', 'd']], ['e', 'd']]

我写了这个功能:

def extract(lst):
    result = []
    result.append(lst)
    for i in lst:
        if isinstance(i, list):
            result.append(i)
            extractt(i)
    return result

但是结果不是预期的。我该如何解决?

python python-3.x list
2个回答
3
投票

您可以对生成器使用递归:

def get_lists(d):
  if isinstance(d, list):
     yield d
     for i in d:
        yield from get_lists(i)

print(list(get_lists(['a', ['b', 'c', ['e', 'd']]])))

输出:

[['a', ['b', 'c', ['e', 'd']]], ['b', 'c', ['e', 'd']], ['e', 'd']]

0
投票

我相信您的代码会丢弃对extract的递归调用的结果。您可以像这样修改它:

def extract(lst):
    result = [lst]
    for i in lst:
        if isinstance(i, list):
            result += extract(i)
    return result
© www.soinside.com 2019 - 2024. All rights reserved.