0

I have list as:

list = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']

I want to check if the string is a foat then it should be converted to float and if the string is a int then it should be converted to int.

Desired Output:

list = [67.50, 70, 72.50, 75, 77.50, 80, 82.5]
Rohit
  • 435
  • 3
  • 10
  • There is a nice list (perhaps outdated, but instructive) about what may and may not parse as a float. But in your case, it may be sufficient to see if there is a decimal point in the number and if not, parse as int else float: `[float(n) if '.' in n else int(n) for n in list]` – smichr Jun 15 '19 at 12:35
  • that one is close too: https://stackoverflow.com/questions/33130279/convert-a-list-of-strings-to-either-int-or-float – Jean-François Fabre Jun 15 '19 at 13:15

4 Answers4

5

You could make use of float.is_integer():

>>> lst = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
>>> [int(x) if x.is_integer() else x for x in map(float, lst)]
[67.5, 70, 72.5, 75, 77.5, 80, 82.5]
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 1
    That map(float, lst) is smart. I also agree with using lst, instead of list as the variable name as list is also a built-in function of Python. – Deepstop Jun 15 '19 at 12:40
2

Here's one way using a list comprehension, and checking if the modulo operator of a given string converted to float is 0.0, to either convert it to float or to integer.

Also note that it is not possible to directly use the built-in int function to construct an integer from a string with decimals, to overcome this I'm using f-strings, where g will print a given number as a fixed-point number, with in this case 0 decimal places:

l = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']

[int(f'{float(i):g}') if float(i)%1 == 0. else float(i) for i in l]
# [67.5, 70, 72.5, 75, 77.5, 80, 82.5]

For python versions under 3.6 use .format for string formatting:

[int('{0:g}'.format(float(i))) if float(i)%1 == 0. else float(i) for i in l]
# # [67.5, 70, 72.5, 75, 77.5, 80, 82.5]
yatu
  • 86,083
  • 12
  • 84
  • 139
1

Well this works, but there's probably a better way. It handles the case like 75.00 which you want to convert to integer and not a float.

from math import floor
list = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
print([int(floor(float(l))) if float(l)-floor(float(l)) == 0 else float(l) for l in list])

Output is

python test.py
[67.5, 70, 72.5, 75, 77.5, 80, 82.5]
Deepstop
  • 3,627
  • 2
  • 8
  • 21
1

Here is another version:

list = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']

new_list = []

for x in list:
    float_x = float(x)
    int_x = int(float_x)
    if int_x == float_x:
        new_list.append(int_x)
    else:
        new_list.append(float_x)

for y in new_list:
    print(type(y))

Returns:

<class 'float'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
kjmerf
  • 4,275
  • 3
  • 21
  • 29