Reputation: 7
I have a list that looks like this:
[[[['0.769', '0.929', '0.977', '1.095', '1.058', '0.864', '0.689', '0.492']], [[0]]], [[['-0.365', '-0.76', '-0.305', '-0.293', '-0.364', '-0.155', '-0.472', '-0.606'], ['-0.296', '-0.503', '-0.454', '-0.868', '-0.721', '-0.918', '-0.486', '-0.582']], [[1]]], [[], [[2]]], [[['-0.246', '-0.935', '-0.277', '-0.175', '-0.278', '-0.075', '-0.236', '-0.417'], ['0.388', '0.329', '0.69', '0.9', '0.626', '0.621', '0.399', '0.37']], [[3]]], [[], [[4]]]]
And I want to turn all these values into floats. The code I tried is:
for x in L:
x=float(x)
Z.append(x)
But when I try this it gives me the following error:
TypeError: float() argument must be a string or a number
Can anybody tell me what I'm doing wrong and how I can fix it? Thanks in advance
Upvotes: 0
Views: 59
Reputation: 1124948
You'd have to traverse the many layers of nesting you have; the outer list contains only more lists.
A recursive solution:
def tofloat(lst):
return [tofloat(i) if isinstance(i, list) else float(i) for i in lst]
Demo:
>>> L = [[[['0.769', '0.929', '0.977', '1.095', '1.058', '0.864', '0.689', '0.492']], [[0]]], [[['-0.365', '-0.76', '-0.305', '-0.293', '-0.364', '-0.155', '-0.472', '-0.606'], ['-0.296', '-0.503', '-0.454', '-0.868', '-0.721', '-0.918', '-0.486', '-0.582']], [[1]]], [[], [[2]]], [[['-0.246', '-0.935', '-0.277', '-0.175', '-0.278', '-0.075', '-0.236', '-0.417'], ['0.388', '0.329', '0.69', '0.9', '0.626', '0.621', '0.399', '0.37']], [[3]]], [[], [[4]]]]
>>> tofloat(L)
[[[[0.769, 0.929, 0.977, 1.095, 1.058, 0.864, 0.689, 0.492]], [[0.0]]], [[[-0.365, -0.76, -0.305, -0.293, -0.364, -0.155, -0.472, -0.606], [-0.296, -0.503, -0.454, -0.868, -0.721, -0.918, -0.486, -0.582]], [[1.0]]], [[], [[2.0]]], [[[-0.246, -0.935, -0.277, -0.175, -0.278, -0.075, -0.236, -0.417], [0.388, 0.329, 0.69, 0.9, 0.626, 0.621, 0.399, 0.37]], [[3.0]]], [[], [[4.0]]]]
This produces a new list with everything that is not a list converted to float
.
Upvotes: 6