Argo Argo - 1 year ago 111
Python Question

Change string to integer in all lists inside a list using Python

I got this:

X = [['0.4,0,6'],['0.2,0,3'],['0.1,0,8']]

And I want to achieve this:

X = [[0.4,0,6],[0.2,0,3],[0.1,0,8]]

I need to make that change because it's causing me a ValueError:

array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: invalid literal for float(): 0.1,0,8

Does anyone have any idea how to make that change?

Answer Source

You have strings in those sublists, which makes it a little confusing. You'll need to split them before converting each item to float:

>>> [[float(i) for i in lst[0].split(',')] for lst in X]
[[0.4, 0.0, 6.0], [0.2, 0.0, 3.0], [0.1, 0.0, 8.0]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download