我有一个以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之类的东西吗?

谢谢


当前回答

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

其他回答

由于Python中的一般准则是请求原谅而不是允许,我认为从序列中检测字符串/标量的最Python的方法是检查它是否包含整数:

try:
    1 in a
    print('{} is a sequence'.format(a))
except TypeError:
    print('{} is a scalar or string'.format(a))

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

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

Preds_test[0]的形状(128,128,1) 让我们使用isinstance()函数检查它的数据类型 Isinstance接受2个参数。 第一个参数是数据 第二个参数是数据类型 isinstance(preds_test[0], np.ndarray)输出为True。这意味着preds_test[0]是一个数组。

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

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

我很惊讶,这样一个基本的问题在python中似乎没有一个直接的答案。 在我看来,几乎所有提出的答案都使用了某种类型 检查,在python中通常不建议这样做,它们似乎仅限于特定的情况(它们失败于不同的数值类型或非元组或列表的泛型可迭代对象)。

对我来说,更好的方法是导入numpy并使用array。尺寸,例如:

>>> a=1
>>> np.array(a)
Out[1]: array(1)

>>> np.array(a).size
Out[2]: 1

>>> np.array([1,2]).size
Out[3]: 2

>>> np.array('125')
Out[4]: 1

还请注意:

>>> len(np.array([1,2]))

Out[5]: 2

but:

>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))

TypeError: len() of unsized object