Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python how to convert number to float in a mixed list [duplicate]

I have a list of strings in the form like

a = ['str','5','','4.1']

I want to convert all numbers in the list to float, but leave the rest unchanged, like this

a = ['str',5,'',4.1]

I tried

map(float,a)

but apparently it gave me an error because some string cannot be converted to float. I also tried

a[:] = [float(x) for x in a if x.isdigit()]

but it only gives me

[5]

so the float number and all other strings are lost. What should I do to keep the string and number at the same time?

like image 212
LWZ Avatar asked Jan 31 '13 19:01

LWZ


2 Answers

>>> a = ['str','5','','4.1']
>>> a2 = []
>>> for s in a:
...     try:
...         a2.append(float(s))
...     except ValueError:
...         a2.append(s)
>>> a2
['str', 5.0, '', 4.0999999999999996]

If you're doing decimal math, you may want to look at the decimal module:

>>> import decimal
>>> for s in a:
...     try:
...         a2.append(decimal.Decimal(s))
...     except decimal.InvalidOperation:
...         a2.append(s)
>>> a2
['str', Decimal('5'), '', Decimal('4.1')]
like image 124
bgporter Avatar answered Sep 28 '22 02:09

bgporter


for i, x in enumerate(a):
    try:
        a[i] = float(x)
    except ValueError:
        pass

This assumes you want to change a in place, for creating a new list you can use the following:

new_a = []
for x in a:
    try:
        new_a.append(float(x))
    except ValueError:
        new_a.append(x)

This try/except approach is standard EAFP and will be more efficient and less error prone than checking to see if each string is a valid float.

like image 32
Andrew Clark Avatar answered Sep 28 '22 01:09

Andrew Clark