I have a list of lists which contain strings of numbers and words I want to convert only those strings which are numbers to floats
aList= [ ["hi", "1.33"], ["bye", " 1.555"] ]
I have a list of lists which contain strings of numbers and words I want to convert only those strings which are numbers to floats
aList= [ ["hi", "1.33"], ["bye", " 1.555"] ]
First, you need a function that does the "convert a string to float if possible, otherwise leave it as a string":
Now, you can just call that on each value, either generating a new list, or modifying the old one in place.
Since you have a nested list, this means a nested iteration. You might want to start by doing it explicitly in two steps:
You can of course combine it into one function just by making
floatify_list
a local function:You could also do it by substituting the inner expression in place of the function call. If you can't figure out how to do that yourself, I would recommend not doing it, because you're unlikely to understand it (complex nested list comprehensions are hard enough for experts to understand), but if you must:
Or, if you prefer your Python to look like badly-disguised Haskell: