[英]How to convert a string containing several float numbers into an array of float in Python?
我有一个文本文件,其中逐行包含浮点字符
15.723
17.567
我尝试阅读文件并在执行此操作后
with open('<path_to_file>/writefile.txt', 'r') as fin:
data_read = fin.read()
当我打印data_read时,我得到
'15.723\n17.567\n'
现在我需要将此字符串保存到包含的数组中
float_array[0]=15.723
float_array[1]=17.567
我该如何进行转换?
我试过了
print(float(data_read))
res = data_read.astype(float)
print(res)
我得到了
ValueError: could not convert string to float: '15.723\n17.567\n'
我在这里做错了什么?
我期待类似 float_array[0]=15.723 float_array[1]=17.567
您可以将文件直接读入字符串列表(使用readlines()
),然后将每一行转换为浮点数。 所以你不必使用split()
with open('<path_to_file>/writefile.txt', 'r') as fin:
data_read = fin.readlines()
numbers = list(map(float, data_read))
首先将您的字符串拆分为单独的数字:
list_of_strings = data_read.split()
现在您可以将float
应用于每个元素:
list_of_floats = [float(x) for x in list_of_strings if x]
如果您的文件以换行符结尾,则检查if x
丢弃最后一个空元素。 如果没有,你可以做
list_of_floats = list(map(float, list_of_strings))
或者您可以先剥离数据:
list_of_strings = data_read.strip().split()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.