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":
def floatify(s):
try:
return float(s)
except ValueError:
return s
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:
def floatify_list(lst):
return [floatify(s) for s in lst]
def floatify_list_of_lists(nested_list):
return [floatify_list(lst) for lst in nested_list]
You can of course combine it into one function just by making floatify_list
a local function:
def floatify_list_of_lists(nested_list):
def floatify_list(lst):
return [floatify(s) for s in lst]
return [floatify_list(lst) for lst in nested_list]
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:
def floatify_list_of_lists(nested_list):
return [[floatify(s) for s in lst] for lst in nested_list]
Or, if you prefer your Python to look like badly-disguised Haskell:
def floatify_list_of_lists(nested_list):
return map(partial(map, floatify), nested_list)