python3 列表扁平化

参考:https://www.cnblogs.com/traditional/p/12422934.html

使用 yield

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]
原文地址:https://www.cnblogs.com/Jaryer/p/15151186.html