我已经看到了关于如何压缩表单列表的几个答案
[1,[1,2],[3]]
print list(itertools.chain(*[1,[1,2],[3]]))
但你如何压扁这样的列表:
[[1],[[1,2],[3]]]
print list(itertools.chain(*[[1],[[1,2],[3]]]))
[1, [1, 2], [3]]
答案 0 :(得分:2)
我通常使用此recipe:
import collections
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, str):
for sub in flatten(el):
yield sub
else:
yield el
print(list(flatten([[1],[[1,2],[3]]])))
# [1, 1, 2, 3]