一切都比没有更大吗?

发布于 2024-08-20 16:07:13 字数 156 浏览 4 评论 0原文

除了None之外,是否还有Python内置数据类型:其中

>>> not foo > None
True

foo是该类型的值? Python 3 怎么样?

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

>>> not foo > None
True

where foo is a value of that type? How about Python 3?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑红尘 2024-08-27 16:07:13

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

在 Python 3 中,这一点发生了改变;现在,在没有合理自然排序的情况下对事物进行比较会导致 TypeError。来自3.0“新增内容”更新

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

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

这让一些人感到不安,因为通常可以很方便地执行一些操作,例如对其中包含一些 None 值的列表进行排序,并使 None 值在开头聚集在一起,或者结尾。 有一个线程不久前,邮件列表上就提到了这一点,但最终的要点是,Python 3 试图避免对排序做出任意决定(这在 Python 2 中经常发生)。

None is always less than any datatype in Python 2 (see 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.0 has simplified the rules for ordering comparisons:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like: 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead 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.

This upset some people since it was often handy to do things like sort a list that had some None values in it, and have the None values appear clustered together at the beginning or end. There was a thread on the mailing list about this a 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).

离笑几人歌 2024-08-27 16:07:13

来自 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;
    ...
}

编辑:添加版本号。

From the Python 2.7.5 source (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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文