Python 任何修复此错误的方法,请在“行”中;std=浮点(行)-平均值错误:无法将字符串转换为浮点;
对于std=float(line)-average-ValueError行:无法将字符串转换为float,我得到上面列出的错误。我试图计算引用列表(RandomNumber.txt)中整数的标准偏差Python 任何修复此错误的方法,请在“行”中;std=浮点(行)-平均值错误:无法将字符串转换为浮点;,python,python-3.x,Python,Python 3.x,对于std=float(line)-average-ValueError行:无法将字符串转换为float,我得到上面列出的错误。我试图计算引用列表(RandomNumber.txt)中整数的标准偏差 欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。此程序需要一个我们没有的数据文件。您应该能够将问题行硬编码到一个列
欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。此程序需要一个我们没有的数据文件。您应该能够将问题行硬编码到一个列表中,并遍历该列表。如果没有其他问题,请提供两行会引发问题的文件行。基本问题可能是行中的某些内容不属于合法浮动的一部分。例如,您是否忘记剥掉线路馈线?
def main():
numbersFile=open("RandomNumber.txt" , 'r')
line=numbersFile.readline()
total=0
numberoflines=0
while line != "":
numberoflines+=1
total+=float(line)
line=numbersFile.readline().strip()
average=total/numberoflines
std=float(line)-average
deviation=float((std**2))/float(numberoflines)
print("The average is: " , average)
print("The standard deviation of the numbers is: ", deviation)
main()
import math
def main():
numbersFile=open("RandomNumber.txt" , 'r')
line=numbersFile.readline()
total=0
numberoflines=0
while line != "":
numberoflines+=1
total+=float(line)
line=numbersFile.readline().rstrip('\n') #had to read the line inside the loop and after converted to float
numbersFile.seek(0) #used .seek(0) to go back and read file from beginning
average=total/numberoflines #removed from loop to calculate final iteraton, instead of creating a new avg every loop
line=numbersFile.readline()
total=0
while line !="": #added this while loop to seperatly calculate the standard deviatoin from the average
line=float(line)-average
a=line**2
total+=a
line=numbersFile.readline()
std=math.sqrt(total/numberoflines)
print("The average is: " , average)
print("The standard deviation of the numbers is: " , std)
main()