Search code examples
pythonreturnreturn-valuenested-lists

I would like to convert data type from within a nested list


Using Jupyter Notebooks/python 3.x; I have been trying to figure out how to convert a string to floats in a list. I am not sure how to best accomplish this and any advice would be much appreciated. I got so far as to converting the individual items but am getting various errors when I try to save the data back into the test list.

my_test_list=[]
my_test_list= [[ '7','8','9','10','11'],['12','13','14','15','16']]

for i in my_test_list:
    for x in i:
        try:
            x=float(x)
            print(x)
        except ValueError:
            pass

print(my_test_list)

Yields the result:

7.0
8.0
9.0
10.0
11.0
12.0
13.0
14.0
15.0
16.0
[['7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16']]

I would like print(my_test_list) to yield the result:

[[7.0, 8.0, 9.0, 10.0, 11.0], [12.0, 13.0, 14.0, 15.0, 16.0]]

Solution

  • You can achieve this one line

    test = [['7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16']]
    
    
    test = [[float(x) for x in l] for l in test]