[英]Python: how to generate a list of "flattened" lists out of a big nested list
假设我有一个如下列表:
[1, 2, [3, 4, [5, 6]], [7, 8], 9]
我想知道如何以下列方式展平这个列表:
[
[7, 8],
[5, 6],
[3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
换句话说,我想知道如何从主列表的每个级别生成一个列表,生成的每个列表都是其所有子列表的扁平版本。
编辑:
如果该方法是左递归方法,则输出的列表很可能具有以下顺序(而不是上面的顺序)的列表:
[
[5, 6],
[3, 4, 5, 6],
[7, 8],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
您可以使用递归生成器函数:
def yield_and_flatten(nested):
"""Yield sublists and flatten, recursively
Produces a boolean and list on each yield; the boolean
flags a merge; sublists are merged just once then
passed down the recursion tree.
"""
if not isinstance(nested, list):
yield True, nested
return
res = []
for elem in nested:
for extend, sub in yield_and_flatten(elem):
if isinstance(sub, list):
if extend:
res.extend(sub)
yield False, sub
else:
res.append(sub)
yield True, res
这会在扩展当前级别之前传递子列表。
演示:
>>> sample = [1, 2, [3, 4, [5, 6]], [7, 8], 9]
>>> for _, res in yield_and_flatten(sample):
... print res
...
[5, 6]
[3, 4, 5, 6]
[7, 8]
[1, 2, 5, 6, 3, 4, 5, 6, 7, 8, 9]
>>> mlist = [1, 2, 3, [[4, [5, 6]], 7], 8, 9]
>>> for _, res in yield_and_flatten(mlist):
... print res
...
[5, 6]
[4, 5, 6]
[4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.