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

后端 未结 4 1717
我在风中等你
我在风中等你 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 16:48

    Just access the first item of the list/array, using the index access and the index 0:

    >>> list_ = [4]
    >>> list_[0]
    4
    >>> array_ = np.array([4])
    >>> array_[0]
    4
    

    This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

    >>> float(list_[0])
    4.0
    

提交回复
热议问题