为什么python中没有最小的?

2024-06-16 12:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我从python学到的东西没有:

None is frequently used to represent the absence of a value

当我把一个列表和数字和字符串排序。我得到了下面的结果,也就是说它是最小的数?在

反转:

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

普通排序:

^{pr2}$

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


Tags: ofthetonone列表排序isvalue
1条回答
网友
1楼 · 发布于 2024-06-16 12:17:46

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

  • None首先排序。在
  • 数字排在其他类型之前,在数字上相互比较。在
  • 其他类型按其类型名称排序,除非它们显式实现比较方法。在

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

Python参考文档中没有记录这一点;请参阅default comparison code in ^{}。它是一个实现细节,而不是你的代码应该依赖的东西。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.

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

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

你的代码会引发一个异常。在

相关问题 更多 >