Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of strings to either int or float

Tags:

python

list

I have a list which looks something like this:

['1', '2', '3.4', '5.6', '7.8']

How do I change the first two to int and the three last to float?

I want my list to look like this:

[1, 2, 3.4, 5.6, 7.8]
like image 336
Johan Fall Avatar asked Oct 14 '15 16:10

Johan Fall


4 Answers

Use a conditional inside a list comprehension

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]

Interesting edge case of exponentials. You can add onto the conditional.

>>> s = ['1', '2', '3.4', '5.6', '7.8' , '1e2']
>>> [float(i) if '.' in i or 'e' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]

Using isdigit is the best as it takes care of all the edge cases (mentioned by Steven in a comment)

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [int(i) if i.isdigit() else float(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
like image 172
Bhargav Rao Avatar answered Nov 15 '22 00:11

Bhargav Rao


Use a helper function:

def int_or_float(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

Then use a list comprehension to apply the function:

[int_or_float(el) for el in lst] 
like image 39
Steven Rumbalski Avatar answered Nov 14 '22 23:11

Steven Rumbalski


Why not use ast.literal_eval?

import ast

[ast.literal_eval(el) for el in lst]

Should handle all corner cases. It's a little heavyweight for this use case, but if you expect to handle any Number-like string in the list, this'll do it.

like image 34
Adam Smith Avatar answered Nov 14 '22 23:11

Adam Smith


Use isdigit method of string:

numbers = [int(s) if s.isdigit() else float(s) for s in numbers]

or with map:

numbers = map(lambda x: int(x) if x.isdigit() else float(x), numbers)
like image 27
Eugene Soldatov Avatar answered Nov 14 '22 22:11

Eugene Soldatov