Python-如何将多维列表排序为二维列表? [英] Python - How to sort multidimensional list to two-dimensional list?
本文介绍了Python-如何将多维列表排序为二维列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何将多维列表排序为二维列表?
How i can sort multidimensional list to two-dimensional list?
多维输入:[8, [6, 7, [-1], [4, [[10]]], 2], 1]
所需的二维输出:[[8, 1], [6, 7, 2], [-1, 4], [], [10]]
所有相同深度列表项都必须位于同一列表中.
all same depth list items need to be in same list.
推荐答案
The idea is basically the same that the one in @TerryA answer, but using setdefault and checking at the end of the for loop if something of the depth was added:
lst = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
def depths(l):
def flatten(l, start=0, depth={}):
for e in l:
if isinstance(e, list):
flatten(e, start=start + 1, depth=depth)
else:
depth.setdefault(start, []).append(e)
if start not in depth:
depth[start] = []
d = {}
flatten(l, depth=d)
return [d[i] for i in range(max(d) + 1)]
result = depths(lst)
print(result)
输出
[[8, 1], [6, 7, 2], [-1, 4], [], [10]]
这篇关于Python-如何将多维列表排序为二维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文