嵌套列表展开
def flatten(nested): if type(nested)==list: for sublist in nested: for i in flatten(sublist): yield i else: yield nested print(list(flatten([[[1],2],3,4,[5,[6,7]],8])))
#结果为[1,2,3,4,5,6,7,8]
树的后序遍历:
def postorderTraversal(self, root): def iter(root): if root: for x in iter(root.left): yield x for x in iter(root.right): yield x yield root.val return list(iter(root))
Python笔记24-----生成器的使用(如嵌套列表的展开、树的遍历等)
原文:https://www.cnblogs.com/Lee-yl/p/9221157.html