正如评论中所指出的,大多数(如果不是全部的话)this 的答案相关问题对于以下列表失败:
ls = [1,2,[3,4]]
此外,列表可以嵌套得更深。如何部分展平到用户给定的级别(默认为无穷大)
ls2 = [1,[2,3],[4,[5,6]]]
ls2
所需的输出:
展平至级别 1:
[1,2,3,4,[5,6]]
扁平化至2级(或更高)
[1,2,3,4,5,6]
最佳答案
你可以递归地做到这一点:
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]
关于python - 将列表部分展平至给定级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948803/