Home > Mobile >  How to convert the elements of a python list of lists?
How to convert the elements of a python list of lists?

Time:05-01

I have a python list (vals) containing lists of strings like this:

[['540.0 ', '0.0 ', '0.0 ', '162.0 ', '2.5 ', '1040.0 ', '676.0 ', '28 ', '79.99 \r'], 

['540.0 ', '0.0 ', '0.0 ', '162.0 ', '2.5 ', '1055.0 ', '676.0 ', '28 ', '61.89 \r'], ...]

When I want to convert its elements with the code below, I get the following error:

ValueError: could not convert string to float

vals = [[float(item) for item in rec] for rec in vals]

How can I solve this problem?

CodePudding user response:

Palliative solution : Not really optimized

It keep only dot and numeric

vals = [[float("".join(_ for _ in item if _.isdigit() or _ == ".")) for item in rec] for rec in vals]

CodePudding user response:

Casting to float from str allows white spaces but not alphabetical characters. A rough solution is str.strip to remove the undesired characters, either at the start or at the end of the string.

l = [['540.0 ', '\r0.0 ', '0.0 ', '\r162.0 \r', '2.5 ', '1040.0 ', '676.0 ', '28 ', '79.99 \r'], ['555']]

new_l = [[float(s.strip('\r')) for s in lst] for lst in l]
print(new_l)
# [[540.0, 0.0, 0.0, 162.0, 2.5, 1040.0, 676.0, 28.0, 79.99], [555.0]]
  • Related