我想从嵌套列表中转换数据类型

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

使用 Jupyter Notebooks/python 3.x;我一直在试图弄清楚如何将字符串转换为列表中的浮点数。我不确定如何最好地完成此任务,我们将不胜感激任何建议。我已经完成了对单个项目的转换,但是当我尝试将数据保存回测试列表时出现了各种错误。

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)

产生结果:

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

我希望print(my_test_list)产生结果:

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

你可以实现这一行

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


test = [[float(x) for x in l] for l in test]

这对 numpy 来说真的又快又简单

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

我同意 Nuno Palma 的回答,但没有解释为什么此代码有效而您的无效。简单地说,您的代码:

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

实际上从未将转换后的 x 保存到 my_test_list。虽然提供的答案更加简洁,但您的代码可以通过简单的添加来工作:

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

接受的答案本质上是 shorthand。