我有一个以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()
>>> 

如你所见,我不能将len应用于P,因为它不是一个数组....python中有isarray或isscalar之类的东西吗?

谢谢


当前回答

在numpy中是否有等效的isscalar() ?是的。

>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True
>>> np.isscalar('abcd')
True

其他回答

另一种替代方法(使用类名属性):

N = [2,3,5]
P = 5

type(N).__name__ == 'list'
True

type(P).__name__ == 'int'
True

type(N).__name__ in ('list', 'tuple')
True

不需要进口任何东西。

要回答标题中的问题,判断变量是否是标量的直接方法是尝试将其转换为浮点数。如果你得到TypeError,它就不是。

N = [1, 2, 3]
try:
    float(N)
except TypeError:
    print('it is not a scalar')
else:
    print('it is a scalar')

你可以检查变量的数据类型。

N = [2,3,5]
P = 5
type(P)

它会给你P的数据类型。

<type 'int'>

这样你就可以区分它是整数还是数组。

前面的回答假设数组是python标准列表。作为一个经常使用numpy的人,我推荐一个非常python化的测试:

if hasattr(N, "__len__")
>>> N=[2,3,5]
>>> P = 5
>>> type(P)==type(0)
True
>>> type([1,2])==type(N)
True
>>> type(P)==type([1,2])
False