我修改了接受的答案的代码,并添加了关键字max_depth,以只将其压平到指定的深度。Max_depth =0表示列表保持原样。也许有人可以用它:
def flatten(l, __depth=0, max_depth=100):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
__depth += 1
if __depth <= max_depth:
yield from flatten(el, __depth=__depth, max_depth=max_depth)
else:
yield el
__depth -= 1
else:
yield el
一些例子:
# A
l = []
depth = 5
for i in range(depth):
el = i
for j in range(i):
el = [el]
l.append(el)
# [0, [1], [[2]], [[[3]]], [[[[4]]]]]
for i in range(depth):
print(list(flatten_gen(l, max_depth=i)))
# [0, [1], [[2]], [[[3]]], [[[[4]]]]]
# [0, 1, [2], [[3]], [[[4]]]]
# [0, 1, 2, [3], [[4]]]
# [0, 1, 2, 3, [4]]
# [0, 1, 2, 3, 4]
# B
l = [[1, 2], [3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13]], 14, [15]]
for i in range(6):
print(list(flatten_gen(l, max_depth=i)))
# [[1, 2], [3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13]], 14, [15]]
# [ 1, 2, 3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13], 14, 15]
# [ 1, 2, 3, 4, 5, 6, [7, [8, [9]]], 10, 12, 13, 14, 15]
# [ 1, 2, 3, 4, 5, 6, 7, [8, [9]], 10, 12, 13, 14, 15]
# [ 1, 2, 3, 4, 5, 6, 7, 8, [9], 10, 12, 13, 14, 15]
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15]