Convert list or numpy array of single element to float in python

后端 未结 4 1716
我在风中等你
我在风中等你 2020-12-14 16:24

I have a function which can accept either a list or a numpy array.

In either case, the list/array has a single element (always). I just need to return a float.

4条回答
  •  生来不讨喜
    2020-12-14 17:00

    Use numpy.asscalar to convert a numpy array / matrix a scalar value:

    >>> a=numpy.array([[[[42]]]])
    >>> numpy.asscalar(a)
    42
    

    The output data type is the same type returned by the input’s item method.

    It has built in error-checking if there is more than an single element:

    >>> a=numpy.array([1, 2])
    >>> numpy.asscalar(a)
    

    gives:

    ValueError: can only convert an array of size 1 to a Python scalar
    

    Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.

提交回复
热议问题