[英]What is the best way to check if a variable is of numeric type in python
I understand that I could use type() and isinstance() to check if a variable is of a certain type or belongs to certain class. 我知道我可以使用type()和isinstance()来检查变量是否属于某种类型或属于某个类。 I was wondering if there is a quick way to check if a variable is of a 'numeric' type, similar to isnumeric in MATLAB. 我想知道是否有一种快速的方法来检查变量是否为“数字”类型,类似于MATLAB中的isnumeric。 It should return True if the variable is int, long, float, double, arrays of ints or floats etc. Any suggestions are greatly appreciated. 如果变量是int,long,float,double,int或float数组等,则应返回True。非常感谢任何建议。
Thank you. 谢谢。
The easiest way to check if an object is a number is to do arithmethic operations (such as add 0) and see if we can get away with it: 检查对象是否为数字的最简单方法是进行算术运算(例如加0),然后看是否可以摆脱它:
def isnumeric(obj):
try:
obj + 0
return True
except TypeError:
return False
print isnumeric([1,2,3]) # False
print isnumeric(2.5) # True
print isnumeric('25') # False
Check to see if each item can be converted to a float : 检查每个项目是否可以转换为float :
def mat_isnumeric(input):
if type(input) is list:
for item in input:
if not is_a_number(item):
return False
return True
else:
return is_a_number(input)
def is_a_number(input):
try:
float(input)
return True
except ValueError:
return False
Running the following script: 运行以下脚本:
if __name__ == "__main__":
print(mat_isnumeric(321354651))
print(mat_isnumeric(3213543.35135))
print(mat_isnumeric(['324234324', '2342342', '2343242', '23432.324234']))
print(mat_isnumeric('asdfasdfsadf'))
print(mat_isnumeric(['234234', '32432.324324', 'asdfsadfad']))
Produces this result: 产生以下结果:
True
True
True
False
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.