首页 > 解决方案 > 对多维点列表进行排序

问题描述

我有一个D 维点列表(其中 D 是一个常数),我想首先根据第一个维度值对它们进行排序,然后根据第二个维度值对它们进行排序,依此类推,所以如果 2 个点具有相同的值在前 x 个维度,它们将根据维度 x+1 的值进行排序。

我知道如果我的维数是最终的,我可以使用这个解决方案:https ://stackoverflow.com/a/37111840 但是由于我有 D 维,其中 D 是代码中的常数,我不确定如何很好地定义排序“关键”值。

标签: pythonlistsorting

解决方案


正如@iz_ 指出的那样,这就是默认情况下 python 排序的工作方式。以下是说明这一点的示例:

import itertools
import random

# generate all length 3 tuples of 0s 1s and 2s
foo = list(itertools.product(*([range(3)]*3)))
#mix them all up
random.shuffle(foo)

print(foo)

# this sorts by the first, then the second, then the last
foo.sort()

print(foo)

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), ( 0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0) , (2, 2, 1), (2, 2, 2)]


推荐阅读