题目:将 下面的列表完全展开,如:list2=[[1,2],[3,4]] 完全展开后为:[1,2,3,4]
list1=[11,[12,[13,14]],[100,200]]
list2=[[1,2],[3,4]]
list3=[[1,2],[3, [4,5,6]]]
way1: 屌丝用法
result = []
def flatten(iter):
if type(iter) is list:
for each in iter:
if isinstance(each,list):
flatten(each)
else:
result.append(each)
else:
result.append(iter)
return result
print(flatten(list1))
#结果:
[11, 12, 13, 14, 100, 200]
way2: 高手写法
list3=[[1,2],[3, [4,5,6]]]
def flatten(iter):
if type(iter) is list:
return [x for each in iter for x in flatten(each)]
else:
return [iter]
print(flatten(list3))
结果:
[1, 2, 3, 4, 5, 6]
way3 :大神写法
list3=[[1,2],[3, [4,5,6]]]
flatten = lambda x: [y for each in x for y in flatten(each) ] if type(x) is list else [x]
print(flatten(list3))
结果:
[1, 2, 3, 4, 5, 6]