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.
So, e.g., I could receive:
list_ = [4]
or the numpy array:
array_ = array([4])
And I should return
4.0
So, naturally (I would say), I employ float(...) on list_ and get:
TypeError: float() argument must be a string or a number
I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.
Based on the success with the numpy array conversion to float this lead me to the approach:
float(np.asarray(list_))
And this works when list_ is both a Python list and when it is a numpy array.
Question
But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?
We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
We can convert the Numpy array to the list by tolist() method, we can have a list of data element which is converted from an array using this method. Returns: The possibly nested list of array elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With