gpt4 book ai didi

python - 为什么None是python中最小的?

转载 作者:IT老高 更新时间:2023-10-28 20:31:53 25 4
gpt4 key购买 nike

我从 python 中学到的无:

None 常用于表示值的缺失

当我放入一个列表并用数字和字符串排序时。我得到了以下结果,这意味着它是最小的数字?

反向:

>>> sorted([1, 2, None, 4.5, (-sys.maxint - 1), (sys.maxint - 1), 'abc'], reverse=True)
['abc', 9223372036854775806, 4.5, 2, 1, -9223372036854775808, None]
>>>

普通排序:

>>> sorted([1, 2, None, 4.5, (-sys.maxint - 1), (sys.maxint - 1), 'abc'])
[None, -9223372036854775808, 1, 2, 4.5, 9223372036854775806, 'abc']
>>>

python 排序函数如何与 None 一起工作?

最佳答案

在比较不同的类型时,CPython 2 应用了一些不同的规则:

  • 首先排序。
  • 数字排在其他类型之前,并在它们之间进行数字比较。
  • 其他类型按其类型名称排序,除非它们显式实现比较方法。

此外,有些类型实现了自定义排序规则,可以拒绝所有排序尝试。例如,当您尝试对复数进行排序时,复数会引发异常,而当您尝试相对于其他类型对复数进行排序时,datetime 对象也会这样做。

这在 Python 引用文档中没有记录;见default comparison code in object.c反而。这是一个实现细节,而不是你的代码应该依赖的东西。 comparison operators documentation状态:

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

目标是在对一系列混合对象进行排序时,使不同类型之间的比较稳定。

在 Python 3 中,比较规则已收紧;您只能比较显式实现比较的对象。经过多年的经验,得出的结论是,允许任意比较只会导致更多的困惑。例如,将带有数字的字符串与整数进行比较总是会让新手感到困惑。

您的代码会引发异常。

关于python - 为什么None是python中最小的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22040724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com