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

后端 未结 14 1335
半阙折子戏
半阙折子戏 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 16:51

    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.

    <type 'int'>
    

    So that you can differentiate that it is an integer or an array.

    0 讨论(0)
  • 2020-12-22 16:53

    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:

    if hasattr(N, "__len__")
    
    0 讨论(0)
  • 2020-12-22 16:53

    Here is the best approach I have found: Check existence of __len__ and __getitem__.

    You may ask why? The reasons includes:

    1. The popular method isinstance(obj, abc.Sequence) fails on some objects including PyTorch's Tensor because they do not implement __contains__.
    2. Unfortunately, there is nothing in Python's collections.abc that checks for only __len__ and __getitem__ which I feel are minimal methods for array-like objects.
    3. It works on list, tuple, ndarray, Tensor etc.

    So without further ado:

    def is_array_like(obj, string_is_array=False, tuple_is_array=True):
        result = hasattr(obj, "__len__") and hasattr(obj, '__getitem__') 
        if result and not string_is_array and isinstance(obj, (str, abc.ByteString)):
            result = False
        if result and not tuple_is_array and isinstance(obj, tuple):
            result = False
        return result
    

    Note that I've added default parameters because most of the time you might want to consider strings as values, not arrays. Similarly for tuples.

    0 讨论(0)
  • 2020-12-22 16:55

    While, @jamylak's approach is the better one, here is an alternative approach

    >>> N=[2,3,5]
    >>> P = 5
    >>> type(P) in (tuple, list)
    False
    >>> type(N) in (tuple, list)
    True
    
    0 讨论(0)
  • 2020-12-22 16:56

    Another alternative approach (use of class name property):

    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.

    0 讨论(0)
  • 2020-12-22 17:02

    Is there an equivalent to isscalar() in numpy? Yes.

    >>> np.isscalar(3.1)
    True
    >>> np.isscalar([3.1])
    False
    >>> np.isscalar(False)
    True
    
    0 讨论(0)
提交回复
热议问题