Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting from string to float or integer depending on their nature in python [duplicate]

After parsing a file, I obtain a list of strings containing numerical values, let's say:

my_list = ['1', '-2.356', '00.57', '0', '-1', '02678', '0.005367', '0', '1']

In order to obtain these numerical values, I do the following:

new_list = [float(i) for i in my_list] . 

The problem is that the integer values - which are a majority in the file I am handling, are also converted to float and thus occupy more memory - let alone other issues (I have to use some of them as indexes - thus they need to be converted to int at some point..)

Is there an efficient way to convert from string to float only those needed (I must not lose any precision) and to integer all the other ones?

like image 263
Matina G Avatar asked Mar 14 '26 20:03

Matina G


1 Answers

You can built a function that converts the strings to integers if possible and floats otherwise (and if even that fails, leave them as strings).

my_list = ['1', '-2.356', '00.57', '0', '-1', '02678', '0.005367', '0', '1']

def converter(n):
  try:
    return int(n)
  except ValueError:
    try:
      return float(n)
    except ValueError:
      return n  # <- left as string

print([converter(x) for x in my_list])  # -> [1, -2.356, 0.57, 0, -1, 2678, 0.005367, 0, 1]

This works because int('2.3') is not the same as int(2.3). The first returns an Error while the second, clips the float and returns 2.

Also note that the order in which the try blocks are arranged is very important since float('2') does work. As a result, casting to int has to be tried first!

like image 93
Ma0 Avatar answered Mar 17 '26 10:03

Ma0