Converting an array of string to array of float
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Mar 25 18:34:58 EDT 2011
On Fri, 25 Mar 2011 08:19:24 -0700, joy99 wrote:
> Dear Group,
>
> I got a question which might be possible but I am not getting how to do
> it.
>
> If I have a list, named,
> list1=[1.0,2.3,4.4,5.5....]
That looks like a list of floats already. Perhaps you meant:
list1 = ["1.0", "2.3", "4.4", "5.5"]
Notice that the elements are now strings, not floats.
> Now each element in the array holds the string property if I want to
> convert them to float, how would I do it?
>
> Extracting the values with for and appending to a blank list it would
> not solve the problem. If appended to a blank list, it would not change
> the property.
I don't understand what you mean. You want to get a list of floats. You
create a list of floats. How does that not solve the problem?
Wait, do you mean you want to change them *in-place*? Like this:
>>> alist = ["1.1", "2.2", "3.3", "4.4", "5.5"]
>>> blist = alist # reference to the same list object
>>> alist[:] = map(float, alist)
>>> print(blist[0] + 1) # prove that it is an in-place change
2.1
The key is the slice assignment: map(float, alist) creates a new list,
but the assignment alist[:] = ... stores those values in the original
list, instead of just binding the name to a new object. It is equivalent
to this:
temp = map(float, alist)
del alist[:] # empty the list in place
alist.extend(temp)
del temp # delete the variable
only easier and faster.
If you don't like map(), you can use a list comprehension:
alist[:] = [float(s) for s in alist]
Finally, if your list is so truly astonishingly huge that you don't have
room for it and the list-of-floats at the same time, hundreds of millions
of items or more, then you can change the list items in place:
for i, s in enumerate(alist):
alist[i] = float(s)
But for small lists and merely large lists (millions or tens of millions)
of items, this will probably be much slower than the solutions shown
above. But your MMV -- time your code and find out for yourself.
--
Steven
More information about the Python-list
mailing list