Python中的奇怪比较

2024-03-29 11:58:23 发布

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

我在胡闹,偶然发现了一些我不明白的东西。。。在

问题1:

a = [1,2,3]
b = [1,2,3,4]

len(a) < b

结果是正确的,但这是否真的比较了两个列表的长度?似乎这也是真的。。。在

^{pr2}$

问题2:

当我们尝试比较整数和列表时会发生什么?为什么这些都是真的(我假设有一个普遍的解释…)。。。在

3 < b
20 < b
float('inf') < b
None < b
(lambda x: (x**x)**x) < b

…这些是假的?在

'poo' < b
'0' < b

Tags: lambdanone列表len整数floatinf时会
3条回答

在Python2.x中,不可直接比较的不同类型的项将使用其类型的名称进行比较。所以所有整数都小于所有列表,因为"int"小于"list"。出于同样的原因,所有str都大于所有ints和{}s

Python3中删除了这种不直观的行为(我假设引入这种行为是为了在异构列表中对类似类型的项进行排序),这为这些比较带来了一个异常。在

来自数据类型上的docs

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

以及

Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. 1 Mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc.

尤其是

Footnotes1 The rules for comparing objects of different types should not be relied upon; they may change in a future version of the language.

其他答案很好地解释了正在发生的事情,但是比较长度的正确方法是

len(a) < len(b)

相关问题 更多 >