Python - 如何将多维列表排序为二维列表?

标签 python list

如何将多维列表排序为二维列表?

多维输入:[8, [6, 7, [-1], [4, [[10]]], 2], 1]

期望的二维输出:[[8, 1], [6, 7, 2], [-1, 4], [], [10]]

所有相同的深度列表项都需要在同一个列表中。

最佳答案

这个想法与@TerryA 回答中的基本相同,但使用 setdefault并在 for 循环结束时检查是否添加了深度内容:

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 - 如何将多维列表排序为二维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632917/

相关文章:

python - 调用一个 python 函数,该函数接受 MATLAB 函数句柄作为来自 matlab 的参数

python - 如何从充满文件名的列表中删除文件扩展名?

html - 使用表单选择标签而不是 iframe

list - 连接列表的有效方法是什么?

list - Prolog 中偶数之和、奇数乘积

python - 将嵌套数据列表转换为多维 Numpy 数组

python - 如何通过 Pandas 而不是从文件加载 pickle

python - Python 有没有模拟键盘操作的库?

python - 使用 1D 变换实现 2D 傅里叶逆变换

Python heapq 与预排序列表的排序速度