如何检查变量是否为整数?


当前回答

下面是这里提到的不同方法的总结:

Int (x) == x 尝试x = operator.index(x) isinstance (x, int) isinstance (x, numbers.Integral)

下面是它们如何应用于各种具有整数值的数值类型:

你可以看到它们不是100%一致的。Fraction和Rational在概念上是相同的,但是一个提供了.index()方法,而另一个没有。复杂类型不喜欢转换为int,即使实部是整数,虚部是0。

(np.int8|16|32|64(5)表示np.int8(5), np.int32(5)等行为相同)

其他回答

import numpy as np

if (np.floor(x)-x == 0):
  return "this is an int"

一种更通用的方法将尝试检查整数和作为字符串给出的整数

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True

如果变量像字符串一样输入(例如。“2010”):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。

这里有一个简单的例子,你可以确定一个整数

def is_int(x):
    print round(x),
    if x == round(x):
        print 'True',
    else:
        print 'False'

is_int(7.0)   # True
is_int(7.5)   # False
is_int(-1)    # True    

考虑x = n**(1.0/m)的情况,其中n=10**5, m=5。 在Python中,x将为10.000000000000002,由于浮点算术运算,它不是整数。

所以我要检查一下

if str(float(x)).endswith('.0'): print "It's an integer."

我用下面的代码进行了测试:

for a in range(2,100):
    for b in range(2,100):
        x = (a**b)**(1.0/b)
        print a,b, x, str(float(x)).endswith('.0')

它对所有a和b输出True。