changing a float inside a nested list

Viewed 53

I'm new to python and I have a small challenge I am facing right now I have this list nested_list = [['1','2','3'],['2','4','6']] I would like to change the strings of the list to their float representation while keeping the order the same it is

new_list = [[1.0,2.0,3.0],[2.0,4.0,6.0]]

thanks for the help

4 Answers

Call float for each item in each nested list:

new_list = [[float(x) for x in lst] for lst in nested_list]

Can also be done using map on the nested lists:

new_list = [list(map(float, lst)) for lst in nested_list]

You can write like as below if you've installed numpy module. In this code for-loop doesn't exist. You don't want to install numpy module just for this though...

import numpy as np
nested_list = [['1','2','3'],['2','4','6']]
new_lst = np.array(nested_list, dtype=np.float).tolist()

Using two loops are not good option for this little task , importing any external module is also not good option:

One line solution without any loop:

nested_list = [['1','2','3'],['2','4','6']]

print(list(map(lambda x:list(map(lambda y:float(y),x)),nested_list)))

output:

[[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]]
Related