1. 程式人生 > >list多層列表展開方法對比

list多層列表展開方法對比

目的:希望展開list為一層
abc=[[2,[1,1,1],2],[3,3,3]]

方法一:https://blog.csdn.net/ytfy12/article/details/51162079

def printm(listin):
    abc = []
    for ie in listin:
        if isinstance(ie,list):
            printm(ie)
        else:
            print(ie)

輸出
2
1
1
1
2
3
3
3

方法二(推薦):參考https://blog.csdn.net/cqk0100/article/details/78320748

def flatten(obj, ignore_itmes=(str, bytes)):
    for item in obj:
        if isinstance(item, list) and not isinstance(item, ignore_itmes):
            yield from flatten(item)
        else:
            yield item
nn = []
for i in flatten(abc):
    nn.append(i)    
print(nn)

輸出[2, 1, 1, 1, 2, 3, 3, 3]