我有一个接受参数的函数 NBins
。我想用一个标量 50
或一个数组 [0, 10, 20, 30]
来调用这个函数。如何在函数内识别 NBins
的长度是多少?或者换一种说法,如果它是标量还是向量?
我试过这个:
>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
>>> len(P)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>>
As you see, I can’t apply len
to P
, since it’s not an array…. Is there something like isarray
or isscalar
在python中?
谢谢
原文由 otmezger 发布,翻译遵循 CC BY-SA 4.0 许可协议
注意:
isinstance
也支持类元组,检查type(x) in (..., ...)
应该避免并且是不必要的。您可能还想检查
not isinstance(x, (str, unicode))
正如 @2080 和 这里 所指出的,这不适用于
numpy
数组。例如。在这种情况下,您可以尝试 @jpaddison3 的答案:
但是,正如 此处 所述,这也不是完美的,并且会错误地将字典(至少根据我)分类为序列,而
isinstance
与collections.abc.Sequence
分类正确:您可以将您的解决方案定制为这样的东西,根据您的需要向
isinstance
添加更多类型: