题
是否有numpy的现有的功能,将告诉我,如果一个值可以是一个数字型或numpy的数组?我正在写这就需要由“号码”来处理在几个不同的表示(数字我的意思是它可以使用标准的算术运算符来操纵一个数值量,的任何表示+,一些数据处理代码 - ,*,/,* *)。
我要寻找的行为的一些例子
>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
如果没有这样的功能存在,我知道它不应该是很难写一个,像
isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
但有其他数字类型我应该包括在列表?
解决方案
正如其他人回答说,有可能是其他数字类型,除了你提到的那些。 一种方法是显式地检查你想要的功能,喜欢的东西
# Python 2
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
# Python 3
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
这适用于除了最后一个,numpy.array(['1'])
你的所有例子。这是因为numpy.ndarray
具有用于数字操作的特殊方法,但引发类型错误,如果你尝试用绳子或对象数组不适当地使用它们。您可以添加一个显式检查该像
... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU')
这可以是足够好的。
不过......你永远不能的 100%的肯定有人会不相同的行为定义另一种类型,所以一个更简单的方法是实际尝试做一个计算,赶上例外,像
def is_numeric_paranoid(obj):
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True
但取决于打算如何经常调用使用它,用什么样的参数,这可能是不实际的(它可以是具有大的阵列可能慢,例如)。
其他提示
在一般情况下,处理未知类型的灵活,快速和Python的方式是对他们只是执行一些操作和捉对无效类型异常。
try:
a = 5+'5'
except TypeError:
print "Oops"
在我看来,这种方法比特套管出一些函数来确定绝对类型的确定性更容易。
此外,numpy的已numpy.isreal
和其他类似的功能(numpy.is
+ Tab键应该列出它们)。
他们都有自己的乐趣角落案件,但其中的一个可能是有用的。
您is_numeric
定义错误。见我的意见你的问题。
其他数值类型可以是:long
,complex
,fractions.Fraction
,numpy.bool_
,numpy.ubyte
,...
operator.isNumberType()
返回True
用于Python号码和numpy.array
。
因为Python 2.6可以使用isinstance(d, numbers.Number)
代替弃用operator.isNumberType()
。
通常最好是检查对象的能力(例如,是否可以的整数添加到它),而不是它的类型。
isinstance(numpy.int32(4), numbers.Number)
返回False
,所以完全不是那么回事。 operator.isNumberType()
不上numpy的数目的所有变体的工作,但是,包括numpy.array([1])
。