从字符串到浮点数 python
From string to float python
我想编写一个代码来读取包含传感器数据的文件。我一开始就卡住了:
import numpy as np
a = []
b = []
x = []
y = []
for line in open("YAZID.txt", "r"):
lines = [i for i in line.split()]
print(lines)
a.append(float(lines[0]))
b.append(float(lines[1]))
for i in a:
i = float(i)
x.append(i)
print(x)
它给我这个错误
['0,375', '7,84E-02']
Traceback (most recent call last):
File "c:\Users\pc orange\Desktop\graphs\graph.py", line 32, in <module>
a.append(float(lines[0]))
ValueError: could not convert string to float: '0,375'
他们被困在字符串中
有没有办法让它们变成浮动的,这样我就可以用它们画图了数字真的很少,我每次都需要读取整数
string= "3.141"
print(string)
print(type(string))
# converting string to float
Float = float(string)
print(Float)
print(type(Float))
您可以将 ,
替换为 .
,然后尝试同样的操作。这是代码:
for line in open("YAZID.txt", "r"):
lines = [i for i in line.split()]
print(lines)
a.append(float(lines[0].replace(",",".")))
b.append(float(lines[1].replace(",",".")))
这样做应该适合你。
此外,您终于不必再float
了,这样做就可以了。
for i in a:
x.append(i)
print(x)
问题出在我的文本文件中,逗号是逗号 (,) 而不是点 (.) 也使用此代码将它们变成浮点数
x = [float(c) for c in a]
感谢大家的帮助
我想编写一个代码来读取包含传感器数据的文件。我一开始就卡住了:
import numpy as np
a = []
b = []
x = []
y = []
for line in open("YAZID.txt", "r"):
lines = [i for i in line.split()]
print(lines)
a.append(float(lines[0]))
b.append(float(lines[1]))
for i in a:
i = float(i)
x.append(i)
print(x)
它给我这个错误
['0,375', '7,84E-02']
Traceback (most recent call last):
File "c:\Users\pc orange\Desktop\graphs\graph.py", line 32, in <module>
a.append(float(lines[0]))
ValueError: could not convert string to float: '0,375'
他们被困在字符串中
有没有办法让它们变成浮动的,这样我就可以用它们画图了数字真的很少,我每次都需要读取整数
string= "3.141"
print(string)
print(type(string))
# converting string to float
Float = float(string)
print(Float)
print(type(Float))
您可以将 ,
替换为 .
,然后尝试同样的操作。这是代码:
for line in open("YAZID.txt", "r"):
lines = [i for i in line.split()]
print(lines)
a.append(float(lines[0].replace(",",".")))
b.append(float(lines[1].replace(",",".")))
这样做应该适合你。
此外,您终于不必再float
了,这样做就可以了。
for i in a:
x.append(i)
print(x)
问题出在我的文本文件中,逗号是逗号 (,) 而不是点 (.) 也使用此代码将它们变成浮点数
x = [float(c) for c in a]
感谢大家的帮助