Skip to content Skip to sidebar Skip to footer

Converting Strings To Floats In A Nested List

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'] ]

Solution 1:

First, you need a function that does the "convert a string to float if possible, otherwise leave it as a string":

deffloatify(s):
    try:
        returnfloat(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:

deffloatify_list(lst):
    return [floatify(s) for s in lst]

deffloatify_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:

deffloatify_list_of_lists(nested_list):
    deffloatify_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:

deffloatify_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:

deffloatify_list_of_lists(nested_list):
    returnmap(partial(map, floatify), nested_list)

Post a Comment for "Converting Strings To Floats In A Nested List"