我们说我有一个如下列表:
[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]
]
答案 0 :(得分:2)
您可以使用递归生成器函数:
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]