In Python, how to convert a number to a float in a mixed list

I have a list of lines in a form like

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

I want to convert all numbers from a list to float, but leave it unchanged, like this

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

I tried

map(float,a)

but apparently this gave me an error because some string could not be converted to float. I also tried

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

but it only gives me

[5]

therefore, the floating point number and all other lines are lost. What should I do to save a string and a number at the same time?

+5
source share
4 answers
for i, x in enumerate(a):
    try:
        a[i] = float(x)
    except ValueError:
        pass

It is assumed that you want to change ain place, to create 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)

try/except EAFP , , , float.

+4
>>> 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]

, :

>>> 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')]
+7

: -

>>> a = ['str','5','','4.1']
>>> import re
>>> [float(x) if re.match("[+-]?(?:\d+(?:\.\d+)?|\.\d+)$", x) else x for x in a]
4: ['str', 5.0, '', 4.1]

, , . , , , , : -

+5

:

def convert(value):
    try:
        return float(value)
    except ValueError:
        return value

map(convert, a)
+3

All Articles