List of strings to list of floats ?

Steve Holden steve at holdenweb.com
Mon Oct 17 12:53:36 EDT 2005


Madhusudan Singh wrote:
> skip at pobox.com wrote:
> 
> 
>>    Madhusudan> Is it possible to convert a very long list of strings to a
>>    Madhusudan> list of floats in a single statement ?
>>
>>    Madhusudan> I have tried float(x) and float(x[:]) but neither work. I
>>    Madhusudan> guess I would have to write a loop if there isn't a way.
>>
>>Try:
>>
>>    >>> los = ["123.0", "2", "1e-6"]
>>    >>> map(float, los)
>>    [123.0, 2.0, 9.9999999999999995e-07]
>>    >>> [float(s) for s in los]
>>    [123.0, 2.0, 9.9999999999999995e-07]
>>
>>Skip
> 
> 
> Thanks. Now, a slightly more complicated question.
> 
> Say I have two lists of floats. And I wish to generate a list of floats that
> is a user defined function of the two lists.
> 
> I tried :
> 
> def rpyth(x,y):
>     r=sqrt(pow(x,2.0)+pow(y,2.0))
>     return r
> 
> r1n=map(rpyth,x2n[1:len(x2n)-1],y2n[1:len(y2n)-1])
> 
> And I get an error complaining about floats.

... but the error message is a secret so you don't want to tell us what 
it was? It's more helpful if you actually copied and pasted the exact 
error traceback you see, as this avoids any potential answerer having to 
guess what went wrong.

A brief description of what you were trying to do is also helpful, since 
it isn't obvious at first glance why you are omitting some of hte list 
elements.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list