Jim421616
Jim421616

Reputation: 1536

converting lots of string lists to floats

I found in this question how to convert a list of strings to floats:

list_of_floats = list(map(lambda x: float(x.replace(",", "")), list_of_string_floats))

I actually have 12 lists to convert:

U_mag = list(map(lambda x: float(x.replace(",", "")), U_mag))
B_mag = list(.........................................B_mag))

etc.

Some of the lists contain items like '-999.000', which I want to convert to a float, while others have items like 'act' or 'QSO', which will be left as strings. Of course, I could write the same line as above 12 times!

I've tried

for item in (U_mag, B_mag, V_mag, R_mag, K_mag, W1_mag,
          W2_mag, W3_mag, W4_mag, L_UV, Q, flag_uv):
    try:
        item = list(map(lambda x: float(x.replace(",", "")), item))
    except:
        pass

This doesn't throw up any errors, but it doesn't change the lists as expected. Surely there's a better way than writing out the same code 12 times.

Where am I going wrong?

Upvotes: 1

Views: 86

Answers (1)

blhsing
blhsing

Reputation: 107124

By assigning the list with a new one you lose the reference to the original list you want to replace.

So instead of:

item = list(map(lambda x: float(x.replace(",", "")), item))

You should assign the new list to a temporary variable, and if it doesn't raise an exception, clear the original list and extend it with the temporary list, so not to lose the original reference:

temp = list(map(lambda x: float(x.replace(",", "")), item))
item.clear()
item.extend(temp)

Upvotes: 2

Related Questions