Christopher Bump
Christopher Bump

Reputation: 13

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

Upvotes: 1

Views: 533

Answers (3)

eric
eric

Reputation: 320

I agree with Nuno Palma's answer, but there is no explanation of why this code works while yours does not. Simply, your code:

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

never actually saves the converted x to my_test_list. While the provided answer is much more concise, your code could work with a simple addition:

output_list = []
for i in my_test_list:
for x in i:
    try:
        x=float(x)
        print(x)
        output_list[i].append(x)
    except TypeError:
        pass

The accepted answer is essentially a shorthand for this.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113948

this is really fast and easy with numpy

import numpy
print(numpy.array([[ '7','8','9','10','11'],['12','13','14','15','16']],dtype=float))

Upvotes: 1

Nuno Palma
Nuno Palma

Reputation: 524

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]

Upvotes: 2

Related Questions