python - 在不同的键上多次使用字典列表排序 - 是否保证保留顺序?

标签 python list sorting python-3.x dictionary

假设您有一个这样的字典列表:

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"])

在最后排序的相同值的项目中(在按 ba 排序之后),是最后排序的项目的顺序保证?我已经测试过了,似乎是这样,但我希望看到这一点得到验证,让我放心。

最佳答案

正如 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/

相关文章:

python - 处理 pandas.datetime 类型时出现消息 "Exception ignored"

python - python 中的编号列表

python - 如何获取每个字符串变体以及每个位置的可能性列表

list - 任何CouchDB _list函数都无法工作

sorting - 按功能编程语言排序

python - 根据相似度最高的值对字典列表进行排序

c# - 如何对泛型类进行排序?

python - 使用迭代器协议(protocol)访问已排序的字典

python - if/elif 语句的语法错误,不确定是什么导致了错误

Python web 文本列表到数据框