• 周六. 7 月 27th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

python3 列表扁平化

admin

11 月 28, 2021

参考: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]

发表回复