如何将字符串列表列表转换为浮点数?

时间:2014-05-10 16:46:17

标签: python string list floating-point

我有一个如下所示的列表:

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

我想把所有这些值变成花车。 我试过的代码是:

for x in L:
    x=float(x)
    Z.append(x)

但是当我尝试这个时它会给我以下错误:

TypeError: float() argument must be a string or a number 

有人能告诉我我做错了什么以及如何解决它?提前致谢

1 个答案:

答案 0 :(得分:6)

你必须遍历你拥有的多层筑巢;外部列表只包含更多列表。

递归解决方案:

def tofloat(lst):
    return [tofloat(i) if isinstance(i, list) else float(i) for i in lst]

演示:

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

这会生成一个 new 列表,其中包含的所有内容都不是转换为float的列表。