简体   繁体   English

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

[英]How to transform a line string in float numbers Python

I have a string line like this way:我有这样的字符串行:

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

How can I put the elements of x in array in float format?如何将x的元素以浮点格式放入数组中? like this:像这样:

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

Given the example str from your question x = '19 0 1.8881 .4928' , you can use the following comprehension to unpack each value as a float into a list ( nums ) for processing as required.鉴于您的问题x = '19 0 1.8881 .4928'的示例str ,您可以使用以下理解将每个值作为float解压缩到list ( nums ) 中,以便根据需要进行处理。

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

If you want to unpack each value to its own list as outlined in your question:如果您想将每个值解压缩到您的问题中概述的自己的列表中:

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

Just change your line from:只需更改您的线路:

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

to:到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM