python:如何识别变量是数组还是标量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16807011/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python: how to identify if a variable is an array or a scalar
提问by otmezger
I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50or an array [0, 10, 20, 30]. How can I identify within the function, what the length of NBinsis? or said differently, if it is a scalar or a vector? 
我有一个接受参数的函数NBins。我想用一个标量50或一个数组调用这个函数[0, 10, 20, 30]。我如何在函数内识别,长度NBins是多少?或者换一种说法,如果它是标量或向量?
I tried this:
我试过这个:
>>> 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 lento P, since it's not an array.... Is there something like isarrayor isscalarin python?
正如你看到的,我不能申请len到P,因为它不是一个数组....有什么样isarray或isscalar在Python?
thanks
谢谢
采纳答案by jamylak
>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False
To support any type of sequence, check collections.Sequenceinstead of list.
要支持任何类型的序列,请检查collections.Sequence而不是list。
note: isinstancealso supports a tuple of classes, check type(x) in (..., ...)should be avoided and is unnecessary.
注意:isinstance也支持类的元组,type(x) in (..., ...)应该避免检查并且是不必要的。
You may also wanna check not isinstance(x, (str, unicode))
您可能还想检查 not isinstance(x, (str, unicode))
回答by Sukrit Kalra
While, @jamylak's approach is the better one, here is an alternative approach
虽然@jamylak 的方法更好,但这是另一种方法
>>> N=[2,3,5]
>>> P = 5
>>> type(P) in (tuple, list)
False
>>> type(N) in (tuple, list)
True
回答by suhailvs
>>> N=[2,3,5]
>>> P = 5
>>> type(P)==type(0)
True
>>> type([1,2])==type(N)
True
>>> type(P)==type([1,2])
False
回答by unnati patil
You can check data type of variable.
您可以检查变量的数据类型。
N = [2,3,5]
P = 5
type(P)
It will give you out put as data type of P.
它会给你输出 P 的数据类型。
<type 'int'>
So that you can differentiate that it is an integer or an array.
这样你就可以区分它是整数还是数组。
回答by Marek
Another alternative approach (use of class nameproperty):
另一种替代方法(使用类名属性):
N = [2,3,5]
P = 5
type(N).__name__ == 'list'
True
type(P).__name__ == 'int'
True
type(N).__name__ in ('list', 'tuple')
True
No need to import anything.
无需导入任何东西。
回答by jpaddison3
Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:
以前的答案假设数组是一个 python 标准列表。作为经常使用 numpy 的人,我推荐一个非常 pythonic 的测试:
if hasattr(N, "__len__")
回答by scottclowe
Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use
将@jamylak 和@jpaddison3 的答案结合在一起,如果您需要对 numpy 数组作为输入保持稳健并以与列表相同的方式处理它们,则应该使用
import numpy as np
isinstance(P, (list, tuple, np.ndarray))
This is robust against subclasses of list, tuple and numpy arrays.
这对于列表、元组和 numpy 数组的子类是健壮的。
And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use
如果您还想对序列的所有其他子类(不仅仅是列表和元组)保持稳健,请使用
import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))
Why should you do things this way with isinstanceand not compare type(P)with a target value? Here is an example, where we make and study the behaviour of NewList, a trivial subclass of list.
为什么要以这种方式与目标值isinstance进行比较而不是type(P)与目标值进行比较?这是一个例子,我们制作并研究 的行为NewList,列表的一个简单子类。
>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True
Despite xand ycomparing as equal, handling them by typewould result in different behaviour. However, since xis an instance of a subclass of list, using isinstance(x,list)gives the desired behaviour and treats xand yin the same manner.
尽管x和y比较相等,处理它们type会导致不同的行为。然而,由于x是的子类的实例list,使用isinstance(x,list)得到所需的行为和治疗x和y以相同的方式。
回答by Vincenzooo
I am surprised that such a basic question doesn't seem to have an immediate answer in python. It seems to me that nearly all proposed answers use some kind of type checking, that is usually not advised in python and they seem restricted to a specific case (they fail with different numerical types or generic iteratable objects that are not tuples or lists).
我很惊讶这样一个基本问题在 python 中似乎没有立即答案。在我看来,几乎所有提议的答案都使用某种类型检查,这在 python 中通常是不建议的,而且它们似乎仅限于特定情况(它们因不同的数字类型或非元组或列表的通用可迭代对象而失败)。
For me, what works better is importing numpy and using array.size, for example:
对我来说,更好的是导入 numpy 并使用 array.size,例如:
>>> 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
Note also:
另请注意:
>>> 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
回答by jmhl
Is there an equivalent to isscalar() in numpy? Yes.
numpy 中是否有与 isscalar() 等效的函数?是的。
>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True
回答by Mathieu Villion
Simply use sizeinstead of len!
只需使用size代替len!
>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

