为什么在Python 1.0中== 1 >>> True; -2.0 == -2 >>>真等等?

Kir*_*kov 0 python floating-point integer python-2.7

我想创造条件,而数字必须是整数.当x == 1.0时,x == int(x)没有帮助...谢谢.

use*_*ica 9

isinstance(x, (int, long))
Run Code Online (Sandbox Code Playgroud)

isinstance测试第一个参数是否是第二个参数指定的一个或多个类型的实例.我们指定(int, long)处理Python自动切换到longs以表示非常大的数字的情况,但是int如果您确定要排除longs,则可以使用.有关更多详细信息,请参阅文档.

至于为什么1.0 == 1,这是因为1.01代表相同的数字.Python不要求两个对象具有相同的类型,以使它们被认为是相同的.

  • 或者如果你也想接受Python的整数接口的第三方实现,你可以做`isinstance(x,numbers.Integral)`.例如,有"gmpy".附带好处,它也适用于Python 3. (2认同)

mic*_*den 5

对 python 来说不是很大,但我用它来检查:

i = 123
f = 123.0

if type(i) == type(f) and i == f:
    print("They're equal by value and type!")      
elif type(i) == type(f):
    print("They're equal by type and not value.")
elif i == f:
    print("They're equal by value and not type.")
else:
    print("They aren't equal by value or type.")
Run Code Online (Sandbox Code Playgroud)

返回:

They're equal by value and not type.
Run Code Online (Sandbox Code Playgroud)