Convert only floating point numbers to int in list python

149 Views Asked by At

I am trying to turn any floating point number in the list 'codes' to an int.

codes = [890.0,'JFR']
codes = [int(c) for c in codes]

I am getting the error:

ValueError: invalid literal for int() with base 10: 'JFR'

What I want the list 'codes' to be is:

[890,'JFR']

My question is how do I change only the floating point numbers to an int without getting the error?

3

There are 3 best solutions below

6
On BEST ANSWER

You should try -

codes = [890.0,'JFR']
codes = [int(c) if isinstance(c, float) else c for c in codes]
0
On

You could make a function that tries to convert to int, and if unsuccessful, returns the original value

def convert_to_int(x):
    try:
        return int(x)
    except ValueError:
        return x

Then call this function for each element in your list.

>>> codes = [890.0,'JFR']
>>> [convert_to_int(i) for i in codes]
[890, 'JFR']
0
On
>>> conversions = [int, str]
>>> codes = [890.0, 'JFR']
>>> converted = [conversion(code)
                 for conversion, code in zip(conversions, codes)]

>>> converted
[890, 'JFR']