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

2024-05-13 19:55:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

['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

但结果并不是预期的那样。我怎么能修好它?你知道吗


Tags: 函数in元素列表forreturnifdef
2条回答

可以对生成器使用递归:

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']]

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

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

相关问题 更多 >