我想使条件比数字必须是整数。并且x == int(x)在x == 1.0时不起作用... 谢谢。为什么在Python 1.0 == 1 >>> True; -2.0 == -2 >>>真等等?
回答
isinstance(x, (int, long))
isinstance
测试的第一个参数是由所述第二参数指定的一种或多种类型的一个实例。我们指定(int, long)
来处理Python自动切换到long
的情况,以表示非常大的数字,但如果您确定要排除long
s,则可以使用int
。有关更多详细信息,请参阅docs。
至于为什么1.0 == 1
,这是因为1.0
和1
代表相同的数字。 Python并不要求两个对象具有相同的类型才能被视为相同。
@ user2864740:哦,对。谢谢。 – user2357112
或者如果你还想接受Python的整数接口的第三方实现,你可以做'isinstance(x,numbers.Integral)'。例如'gmpy'。附带的好处,它也适用于Python 3。 –
上蟒并不大,但我用这个来检查:
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.")
返回:
They're equal by value and not type.
@downvoter这个答案有什么问题?它编译并回答了这个问题。 – michaelsnowden
不是由我投票,但这可能是因为在Python中检查绝对类型是不鼓励的。这太精确了。它不考虑Python 2中的两个整数类型或任何子类。 'isinstance()'通常是你想要的。 –
就检查它是否是一个整数。
>>> def int_check(valuechk, valuecmp):
if valuechk == valuecmp and type(valuechk) == int:
return True
else:
return False
>>> int_check(1, 1)
True
>>> int_check(1.0, 1)
False
- 1. 为什么-2 >>> 1等于2147483647的Java
- 2. 为什么-1 >> 1是-1?而1 >> 1是0!
- 3. 为什么(-1 >>> 32)= -1?
- 4. 1 ==(int)0.5 * 2 => false,1 ==((int)0.5 * 2)=> true,为什么?
- 5. 305419896 >> 28等于1?
- 6. 3> 2> 1为真的语言
- 7. 为什么Python 2.7中的`()>''> []> {}> 0> None`?
- 8. 为什么10 >> 2 + 5 >> 2评估为零?
- 9. 什么2> 1>的/ dev/null,并且2>&1>/dev的差异/空
- 10. (-1 >> 1)== -1 - 为什么?
- 11. 为什么(1 >> 0x80000000)== 1?
- 12. (-1 >>> 32)== -1?
- 13. 为什么5> 4> 3!=(5> 4 && 4> 3)在Javascript中为true?
- 14. Python解释器中的>>> >>> some_object和print >>> some_object有什么不同?
- 15. Python:>> =做什么?
- 16. 为什么〜0 >> 1不移位?
- 17. >>和>>>在Java中意味着什么?
- 18. 吨> = 1或T> = 2 => T> = 1
- 19. 为什么(0x7FFFFFFF >> 31)+ 1是零?
- 20. JavaScript:真的如何>> 0 = 1?
- 21. 为什么<< 256 :: size(16)>>目前为<<1, 0>>?
- 22. 拿什么>>>字符在JavaScript
- 23. >>>在JavaScript中做什么?
- 24. python中的双重不等式(>>)是什么?
- 25. '>>>'在JavaScript中表示什么?
- 26. 为什么<$>和<*>的输入顺序是>> =?
- 27. get_post_meta($ post-> ID,“agent_value”,true); ?>
- 28. 为什么 “警报(3> 2> 1)” 警惕 “假”
- 29. 浮动(一 - > a)中,NUM(一 - >一 - >一)等在Haskell
- 30. 为什么在Python中'> 0 True?
为什么不是真的? –
你的意思是你想确保x是一个整数? – Keith
@Keith Integer可能是合适的 - '1.0'也是一个整数。 – user2864740