我有一个脚本,读取一个文本文件,拉出小数作为字符串,并将它们放入一个列表。

所以我列出了这个清单:

my_list = ['0.49', '0.54', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']

如何将列表中的每个值从字符串转换为浮点数?

我试过:

for item in my_list:
    float(item)

但这似乎对我不起作用。


当前回答

换做是我就会这么做。

my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', 
    '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
    '0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>

其他回答

这将是另一个方法(不使用任何循环!):

import numpy as np
list(np.float_(list_name))

我已经解决了这个问题在我的程序使用:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)

Map (float, mylist)可以做到。

(在Python 3中,map停止返回一个列表对象,所以如果你想要一个新的列表,而不仅仅是要迭代的东西,你要么需要list(map(float, mylist) -要么使用SilentGhost的答案,这可以说是更Python化的。)

[float(i) for i in lst]

准确地说,它创建了一个带有浮点值的新列表。与映射方法不同,它将在py3k中工作。

可以使用numpy将列表直接转换为浮动数组或矩阵。

    import numpy as np
    list_ex = [1, 0] # This a list
    list_int = np.array(list_ex) # This is a numpy integer array

如果要将整数数组转换为浮动数组,则添加0。它

    list_float = np.array(list_ex) + 0. # This is a numpy floating array