[Solved] Python- converting to float using map()


It’s ugly, but yeah, it can be done:

my_list=[['Hello', 1 , 3],['Hi', 4 , 6]]

print(list(map(lambda lst: list(map(lambda x: float(x) if type(x) == int else x, lst)), my_list)))

# Output: [['Hello', 1.0, 3.0], ['Hi', 4.0, 6.0]]

EDIT

I personally prefer list comprehension in most cases as opposed to map/lambda, especially here where all the conversions to lists are annoying:

print([
    [float(x) if type(x) == int else x for x in lst]
    for lst in my_list
])

EDIT 2

And finally, an in-place solution that uses good old for loops:

for lst in my_list:
    for i, item in enumerate(lst):
        if type(item) == int:
            lst[i] = float(item)

print(my_list)

4

solved Python- converting to float using map()