假设您有一个这样的字典列表:
x = [{"a":1,"b":2,"c":3},{"a":3,"b":2,"c":4},{"a":2,"b":1,"c":4},{"a":1,"b":3,"c":1}]
并且您想按 a
的优先级排序,然后是 b
,然后是 c
,因此从逻辑上讲,您可以按相反的方式排序:
x = sorted(x, key = lambda x: x["c"])
x = sorted(x, key = lambda x: x["b"])
x = sorted(x, key = lambda x: x["a"])
在最后排序的相同值的项目中(在按 b
或 a
排序之后),是最后排序的项目的顺序保证?我已经测试过了,似乎是这样,但我希望看到这一点得到验证,让我放心。
最佳答案
正如 list
类型的文档所说:
The
sort()
method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
关于python - 在不同的键上多次使用字典列表排序 - 是否保证保留顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35478046/