Python lambda函数中的float身份比较 [英] float identity comparison in Python lambda function
问题描述
为什么Python的lambda会发生以下情况(在Python 2和3中都是如此)?
Why does the following happen with Python's lambdas (in both Python 2 and 3)?
>>> zero = lambda n: n is 0
>>> zero(0)
True
>>> zero = lambda n: n is 0.0
>>> zero(0.0)
False
推荐答案
最常见的Python实现在预分配的数组中将许多小整数存储为常量"或永久"对象:请参见文档.因此,可以使用is
运算符将这些数字识别为相同的对象.浮点数未完成此操作.
The most common Python implementation store a number of small integers as "constant" or "permanent" objects in a pre-allocated array: see the documentation. So, these numbers can be recongized as identical objects using the is
operator. This is not done for floats.
如果使用相等运算符==
比较数字,则对int和float的行为将相同.
If you were to compare the numbers using the equality operator ==
, you'd get identical behaviour for ints as well as floats.
请注意,0
是整数,而0.0
是浮点数.
Note that 0
is an integer, and 0.0
is a float.
如果要使用更大的整数而不是0
(例如,更改lambda以测试n is 5000
,并且还将5000
插入到函数中),它将再次返回False
,因为这两个5000
数字在内部将是不同的对象.
If you were to use a larger integer instead of 0
(for example, changing the lambda to test for n is 5000
, and also plugging 5000
into the function), it would return False
again, because the two 5000
numbers would be different objects internally.
为清楚起见,有一些例子:
Some examples for clarity:
>>> zero = lambda n: n is 0
>>> zero(0)
True
is
在这里返回True
,因为0
的两个实例在内部实际上是相同的对象(这是is
检查的对象).
is
returns True
here because both instances of 0
are literally the same object internally (which is what is
checks for).
>>> zero = lambda n: n == 0
>>> zero(0)
True
==
这次返回True
是因为两个数字相等,而不一定是因为它们在内部是相同的对象.
==
returns True
this time because the two numbers are equal, not necessarily because they are identical objects internally.
>>> zero = lambda n: n is 5000
>>> zero(5000)
False
这将返回False
,因为5000
的数字太大,它不再适合内部预先分配的数字范围.
This returns False
because 5000
is too big a number, it no longer fits in the range of numbers that get pre-allocated internally.
>>> zero = lambda n: n is 0.0
>>> zero(0.0)
False
这再次返回False
,因为0.0
是一个浮点数,对于浮点数,内部没有任何预分配,就像有限范围的整数一样,因此实际上与上面的情况完全相同.
This returns False
again because 0.0
is a float, and for floats there isn't any pre-allocating internally like there is for a limited range of integers, so this is actually exactly the same case as above.
>>> zero = lambda n: n == 0.0
>>> zero(0.0)
True
使用==
而不是is
会导致再次比较数字而不是内部对象,因此现在得到True
.
Using ==
instead of is
results in comparing the numbers again instead of internal objects, so now we get True
.
这篇关于Python lambda函数中的float身份比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!