递归生成器
python基础教程中(第2版 修订版)p155页有这样一段代码:
def flatten(nested): try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested list(flatten([[[1], 2], 3, 4, [5, [6, 7]], 8])) 输出: [1, 2, 3, 4, 5, 6, 7, 8]
这是递归生成器的使用。其它递归生成器可参考 filter函数与无限生成器结合使用遇到的问题 。
调试代码:
def flatten(nested): try: print(nested) for sublist in nested: print('\n') print(sublist) for element in flatten(sublist): print(element) yield element except TypeError: yield nested list(flatten([[[1], 2], 3, 4, [5, [6, 7]], 8])) 输出: [[[1], 2], 3, 4, [5, [6, 7]], 8] [[1], 2] [[1], 2] [1] [1] 1 1 1 1 1 2 2 2 2 3 3 3 4 4 4 [5, [6, 7]] [5, [6, 7]] 5 5 5 5 [6, 7] [6, 7] 6 6 6 6 6 7 7 7 7 7 8 8 8 [1, 2, 3, 4, 5, 6, 7, 8]
可见,其中的yield nested用于生成每个最终的输出值,而其中yield element的作用是向上传递yield nested的值,相当于接力器,所以每个值print(element)输出的数量不一样,越多说明递归调用的越深,需要传递的层数越多。