Python 巢狀列表展開
阿新 • • 發佈:2019-02-11
問題1:對於列表形如 list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] 轉化成列表 list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9] 的問題。
Python實現:
# 普通方法 list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] list_2 = [] for _ in list_1: list_2 += _ print(list_2) # 列表推導 list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] list_2 = [i for k in list_1 for i in k] print(list_2) # 使用sum list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] list_2 = sum(list_1, []) print(list_2)
問題2:對於複雜一些的,如:list =[1,[2],[[3]],[[4,[5],6]],7,8,[9]],上面的方法就不好使了。得換個方法了,這裡使用遞迴的方法解決。
Python實現:
def flat(nums):
res = []
for i in nums:
if isinstance(i, list):
res.extend(flat(i))
else:
res.append(i)
return res