参考:https://www.cnblogs.com/traditional/p/12422934.html
yield 返回的是一个迭代器,所以要用列表推导式将所有元素提取到列表中去。
def flatten(l: list)-> iter: """将列表扁平化""" for _ in l: if isinstance(_, list): yield from flatten(_) else: yield _ >>> list1 = [1,2,3,[33,41,331,4,1,[1,2,3],3,[1]]] >>> list2 = [_ for _ in flatten(list1)] >>> list2 [1, 2, 3, 33, 41, 331, 4, 1, 1, 2, 3, 3, 1]