convert element in a list to float

Denis McMahon denismfmcmahon at gmail.com
Sun Sep 13 19:43:11 EDT 2015


On Sun, 13 Sep 2015 23:02:55 +0200, Laura Creighton wrote:

> In a message of Sun, 13 Sep 2015 12:55:13 -0700, forums_mp at hotmail.com
> writes:
>>
>>For starters, I googled and saw a plethora of writings on how to convert
>>an entire list from string to float.   My interest is on select elements
>>in the list.  The output from the print statement: print scenarioList
>>  
>>is as follows
>>
>>[ '3000000', '"N"', '11400000', '"E"' ]
>>
>>I need to convert the first and third element to float.
>>  lat = ( float ) scenarioList [ 0 ]
>>  lon = ( float ) scenarioList [ 2 ]
>>
>>fails (invalid syntax).  How can I achieve my objective.
>>
>>Thanks in advance
> 
> Does this help?
> 
>>>> l = [ '3000000', '"N"', '11400000', '"E"' ]
>>>> [float(l[0]), l[1], float(l[2]), l[3]]
> [3000000.0, '"N"', 11400000.0, '"E"']

Here's a method that will convert any value in a list that can be made a 
float into a float, and (I think) should leave all others as they are. It 
users a helper function and a list comprehension.

>>> def tofloat(x):
...     try:
...         return float(x)
...     except ValueError:
...         return None
... 
>>> l = [ '3000000', '"N"', '11400000', '"E"' ]
>>> l = [ tofloat(x) or x for x in l ]
>>> l
[3000000.0, '"N"', 11400000.0, '"E"']

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list