发布于 4年前

Python 展开嵌套的列表

有时,您不确定列表的嵌套深度,只希望将所有元素放在一个平面列表中。

from iteration_utilities import deepflatten
# if you only have one depth nested_list, use this
def flatten(l):
  return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]
print(flatten(l))
# [1, 2, 3, 3]
# if you don't know how deep the list is nested
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果有正确格式化的数组,则`Numpy Flatten`是执行此操作的更好方法。
©2020 edoou.com   京ICP备16001874号-3