3 回答
TA贡献1946条经验 获得超4个赞
为什么不是简单的循环:
>>> L = [1,2,3,(4,5,6),[7,8,9]]
>>> L2 = []
>>> for i in L:
if isinstance(i,list):
L2.extend(i)
else:
L2.append(i)
>>> L2
[1, 2, 3, (4, 5, 6), 7, 8, 9]
>>>
TA贡献1854条经验 获得超8个赞
def flatten(arr):
if not isinstance(arr, list):
return arr
else:
output = []
for sy in arr:
if isinstance(sy, list):
temp = flatten(sy)
for py in temp:
output.append(py)
else:
output.append(sy)
return output
print (flatten([1,2,3,(4,5,6),[7,8,9]]))
#[1, 2, 3, (4, 5, 6), 7, 8, 9]
TA贡献1772条经验 获得超5个赞
试试看:
f = lambda *n: (e for a in n
for e in (f(*a) if isinstance(a, (list)) else (a,)))
print(list(f([1,2,3,(4,5,6),[7,8,9]])))
# [1, 2, 3, (4, 5, 6), 7, 8, 9]
添加回答
举报