python: how to identify if a variable is an array or a scalar

后端 未结 14 1338
半阙折子戏
半阙折子戏 2020-12-22 16:13

I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50 or an array [0, 10, 20, 30].

14条回答
  •  粉色の甜心
    2020-12-22 17:03

    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

    import numpy as np
    isinstance(P, (list, tuple, np.ndarray))
    

    This is robust against subclasses of list, tuple and numpy arrays.

    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 isinstance and 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.

    >>> 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)
    
    >>> type(x) is list
    False
    >>> type(y) is list
    True
    >>> type(x).__name__
    'NewList'
    >>> isinstance(x, list)
    True
    

    Despite x and y comparing as equal, handling them by type would result in different behaviour. However, since x is an instance of a subclass of list, using isinstance(x,list) gives the desired behaviour and treats x and y in the same manner.

提交回复
热议问题