字典在python 3中不可排序? [英] dicts are not orderable in python 3?

查看:137
本文介绍了字典在python 3中不可排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么字典在python2中可排序,但在python3中不排序?我在文档的任何地方都找不到它.

Why are dicts orderable in python2, but not in python3? I can't find it anywhere in the documentation.

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()

vs.

Python 2.7.6 (default, Feb 26 2014, 12:01:28)
>>> sorted([{'a':'a'},{'b':'b'}])
[{'a': 'a'}, {'b': 'b'}

推荐答案

Python 2使用未记录的排序,该实现为<一种href ="http://docs.python.org/2/reference/datamodel.html#object.__cmp__" rel ="noreferrer"> .__cmp__() 特殊方法.

Python 2 uses an undocumented ordering, implemented as a .__cmp__() special method.

排序仅在有限的用例中才有意义,并且仅存在是因为Python 2试图使一切可排序.

The ordering only makes sense in a limited set of use-cases, and only exists because Python 2 tries to make everything orderable.

Python 3 彻底清理了Python的订购故事.__cmp__()消失了,现在只有真正具有自然顺序的类型(例如数字和字符串)才支持顺序.对于其他所有内容,您都需要明确定义顺序.

Python 3 drastically cleaned up Python's ordering story; .__cmp__() is gone, and only types that actually have a natural ordering (such as numbers and strings) now support ordering. For everything else, you'll need to explicitly define an ordering.

字典没有自然顺序.如果确实需要对字典进行排序,则需要定义一个对您的用例有意义的显式顺序.如果这意味着仅比较键,请这样做(例如使用key=sorted),等等.

Dictionaries do not have a natural ordering. If you do need to order dictionaries, you need to define an explicit order that makes sense for your use case. If that means comparing just the keys, do so (e.g. use key=sorted), etc.

这篇关于字典在python 3中不可排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆