gpt4 book ai didi

python - 为什么空字典大于 1?

转载 作者:太空狗 更新时间:2023-10-29 17:03:52 25 4
gpt4 key购买 nike

为什么下面的代码是正确的?

>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False

我知道我想要的是 len(foo) > 1,但作为初学者,这让我感到惊讶。

最佳答案

来自docs :

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__, described in section 3.4.

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)

关于python - 为什么空字典大于 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17284326/

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