python - 对多维点列表进行排序
问题描述
我有一个D 维点列表(其中 D 是一个常数),我想首先根据第一个维度值对它们进行排序,然后根据第二个维度值对它们进行排序,依此类推,所以如果 2 个点具有相同的值在前 x 个维度,它们将根据维度 x+1 的值进行排序。
我知道如果我的维数是最终的,我可以使用这个解决方案:https ://stackoverflow.com/a/37111840 但是由于我有 D 维,其中 D 是代码中的常数,我不确定如何很好地定义排序“关键”值。
解决方案
正如@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)]
推荐阅读
- java - 我需要为此在 recyclerview 中创建一个 recyclerview 吗?
- php - 单实例 v2 的方法覆盖
- javascript - node.js 的 fs 模块 writeFile 方法不是函数吗?
- python-3.x - os.system() 是在 Python 脚本中获取一组文件的最佳方法吗?
- python-3.x - 如何忽略 sympy.solve 复杂的解决方案
- python - Jupyter Book,如何更改字体或间距(文本格式)
- javascript - 使用反应上下文的问题
- c++ - Memcpy 数据直接存入 std::vector
- ssis - SSIS Azure 工具在 VS2019 Azure SSIS 工具箱中显示为灰色
- spring-boot - 网关处的 Prometheus 指标:未知而不是 uri 中的路径