我有一个嵌套列表。例如:
['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
但是结果不是预期的。我该如何解决?
您可以将递归与生成器一起使用:
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']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句