2 回答
TA贡献1804条经验 获得超7个赞
你可以递归地做到这一点:
def flatten(l, level=None):
if level == 0:
return l
flattened = []
for item in l:
if isinstance(item, list):
flattened.extend(flatten(item, level-1 if level is not None else None))
else:
flattened.append(item)
return flattened
ls2 = [1,[2,3],[4,[5,6]]]
print(flatten(ls2, level=1))
# [1, 2, 3, 4, [5, 6]]
print(flatten(ls2, level=2))
# [1, 2, 3, 4, 5, 6]
print(flatten(ls2))
# [1, 2, 3, 4, 5, 6]
TA贡献2039条经验 获得超7个赞
一种方法
ls2 = [1,[2,3],[4,[5,6]]]
def make_list_of_list(a):
return [[i]if not isinstance(i, list) else i for i in a]
def flatten(l):
return [item for sublist in make_list_of_list(l) for item in sublist]
flatten(ls2) will result in [1, 2, 3, 4, [5, 6]]
flatten(flatten(ls2)) will result in [1, 2, 3, 4, 5, 6]
添加回答
举报