python 一切都大于无吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2214194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:04:51  来源:igfitidea点击:

Is everything greater than None?

pythonpython-3.xpython-datamodel

提问by Attila O.

Is there a Python built-in datatype, besides None, for which:

除了None,是否有 Python 内置数据类型,为此:

>>> not foo > None
True

where foois a value of that type? How about Python 3?

foo该类型的值在哪里?Python 3 怎么样?

回答by John Feminella

Noneis always less than any datatype in Python 2 (see object.c).

None始终小于 Python 2 中的任何数据类型(请参阅 参考资料object.c)。

In Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a TypeError. From the 3.0 "what's new" updates:

在 Python 3 中,这被改变了;现在对没有合理自然排序的事物进行比较会导致TypeError. 从3.0“新功能”更新开始

Python 3.0 has simplified the rules for ordering comparisons:

The ordering comparison operators (<, <=, >=, >) raise a TypeErrorexception when the operands don't have a meaningful natural ordering. Thus, expressions like: 1 < '', 0 > Noneor len <= lenare no longer valid, and e.g. None < Noneraises TypeErrorinstead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the ==and !=operators: objects of different incomparable types always compare unequal to each other.

Python 3.0 简化了排序比较的规则:

当操作数没有有意义的自然排序时,排序比较运算符 ( <, <=, >=, >) 会引发TypeError异常。因此,像: 1 < '', 0 > Noneor这样的表达式len <= len不再有效,例如None < NoneraisesTypeError而不是 return False。一个推论是对异构列表进行排序不再有意义——所有元素必须相互比较。请注意,这不适用于==and!=运算符:不同不可比较类型的对象总是相互比较不相等。

This upset some people since it was often handy to do things like sort a list that had some Nonevalues in it, and have the Nonevalues appear clustered together at the beginning or end. There was a thread on the mailing list about thisa while back, but the ultimate point is that Python 3 tries to avoid making arbitrary decisions about ordering (which is what happened a lot in Python 2).

这让一些人感到不安,因为这样做通常很方便,例如对包含一些None值的列表进行排序,并让这些None值在开头或结尾聚集在一起。不久前,邮件列表上有一个关于此的主题,但最终的一点是 Python 3 试图避免对排序做出任意决定(这在 Python 2 中经常发生)。

回答by Torsten Marek

From the Python 2.7.5source (object.c):

来自 Python 2.7.5源代码 ( object.c):

static int
default_3way_compare(PyObject *v, PyObject *w)
{
    ...
    /* None is smaller than anything */
    if (v == Py_None)
            return -1;
    if (w == Py_None)
            return 1;
    ...
}

EDIT: Added version number.

编辑:添加了版本号。