python's docs

2.3.1 构造一个递归的生成器


1. 简单的生成器

>>> def simpleGen(nested):
...     for sublist in nested:
...         for element in sublist:
...             yield element
...

>>> nested = [[1, 2], [3, 4], [5]]

>>> list(simpleGen(nested))
[1, 2, 3, 4, 5]

示例中,我们使用生成器解析了一个基本元素为list的list,但是我们只能使用此函数来解析元素全部为list的list,而且嵌套list只能是一层。


2. 递归的生成器

为了解决上面生成器不能解决的问题(无法动态的递归解析复杂list),我们写一个递归的生成器

>>> def recursiveGen(nested):
...     try:
...         for sublist in nested:
...             for element in recursiveGen(sublist):
...                 yield element
...     except TypeError:
...         yield nested
...

>>> nested2 = [1, [2, 3], [[4, [5, 6]], 7], 8, (9, (10, 11))]

>>> list(recursiveGen(nested2))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]