python - 在 Python 中对多维列表进行深度排序的最有效/最干净的方法是什么?

标签 python arrays list sorting multidimensional-array

示例:
来自这个列表:

list = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]]

我想要:

print list
[[1, 1, 1], [2, 4, 9], [10, 11, 16]]

list.sort() 函数是否可行,还是我必须编写自定义循环?

最佳答案

这是一个展平、排序然后重建嵌套列表的示例,正​​如@Inerdia 在上面的评论中所建议的那样。

我尝试尽可能使用生成器和迭代器,但我确信有更聪明、更有效的方法来获得结果!

from itertools import izip

l = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]]
# flatten the list and sort it
f = sorted(inner for outer in l for inner in outer)
# group it into 3s again using izip
new_list = [list(l) for l in izip(*[iter(f)]*3)]

关于python - 在 Python 中对多维列表进行深度排序的最有效/最干净的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988310/

相关文章:

javascript - 检索两个列表,对值进行排序和比较,然后显示所有结果

在 R 中重新格式化数据框

python - 在 python 中编程时钟时,如何允许用户输入自己的当前时间值?

javascript - JS - 递归 - 遍历对象图返回找到的对象并保存路径

python - 单线程代码中垃圾收集器导致的自死锁

ruby 按键对数组中的值求和

java - 将数据存储到对象数组元素中返回 NullPointerException

python - `yield from` 生成器与 `yield from` 列表性能

python - 如何在 or-tools 中定义复杂的目标函数?

python - 为什么 Scrapy Udemy 给出响应 403 错误?