为什么字典在 python2 中可以排序,但在 python3 中不行?我在文档中的任何地方都找不到它。
Python 3.3.4 (default, Feb 11 2014, 16:14:21)
>>> sorted([{'a':'a'},{'b':'b'}])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()
对比
Python 2.7.6 (default, Feb 26 2014, 12:01:28)
>>> sorted([{'a':'a'},{'b':'b'}])
[{'a': 'a'}, {'b': 'b'}
最佳答案
Python 2 使用 undocumented ordering , 实现为 .__cmp__()
特殊方法。
排序仅在一组有限的用例中有意义,并且只存在于 Python 2 试图使一切可排序。
python 3 drastically cleaned up Python's ordering story ; .__cmp__()
消失了,现在只有真正具有自然排序的类型(例如数字和字符串)才支持排序。对于其他一切,您需要明确定义顺序。
字典没有自然顺序。如果您确实需要对字典进行排序,则需要定义一个对您的用例有意义的明确顺序。如果这意味着只比较键,那么就这样做(例如使用 key=sorted
),等等。
关于python - 字典在 python 3 中不可订购?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333388/