如何在浮点数Python中转换字符串



我有一个字符串行,如下所示:

f=open(flowsrc.baseflowpath+flowsrc.baseflowfile,"r")
lines=f.readlines()[1:] #jump the first line
result=[]
for x in lines:
result.append(x.split(' ')[0])
f.close()
print x, type(x)
out: 19     0       1.8881      .4928
out: <type 'str'>

如何将x的元素以浮点格式放入数组中?像这样:

a = [19.0]
b = [0.0]
c = [1.8881]
d = [0.4928]

给定问题x = '19 0 1.8881 .4928'中的示例str,您可以使用以下理解将每个值作为float解压缩为list(nums(,以便根据需要进行处理。

nums = [ float(i) for i in x.split(' ') if i != '' ]

如果您想将每个值解压到自己的列表中,如您的问题所述:

a = [nums[0]]
b = [nums[1]]
c = [nums[2]]
d = [nums[3]]

只需更改您的行即可:

result.append(x.split(' ')[0])

至:

result.append(float(x.split(' ')[0]))

最新更新