Python + 不支持的操作数类型:“float”和“str”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35393303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unsupported operand type(s) for +: 'float' and 'str' error
提问by Usman Khan
I am new to Python and am stuck with what to do right now because I keep getting this error. I am trying to add the contents of the score file together and get an average but I can't seem to get it to work.
我是 Python 的新手,并且坚持现在要做的事情,因为我不断收到此错误。我试图将分数文件的内容加在一起并获得平均值,但我似乎无法让它工作。
My code:
我的代码:
# open and read file student / score
student_file = open("Student.txt", "r")
score_file = open("Score.txt", "r")
student = student_file.read().split(' ')
score = score_file.read().split(' ')
addedScore = 0.0
average = 0.0
for i in range(0,len(student)):
print("Student: "+student[i]+" Final: "+score[i])
addedScore = addedScore + score[i]
average = addedScore / 2
print("The class average is:", average)
The score file is full of float numbers:
分数文件充满了浮点数:
90.0 94.0 74.4 63.2 79.4 87.6 67.7 78.1 95.8 82.1
The error message
错误信息
line 12, in <module>
addedScore = addedScore + score[i]
TypeError: unsupported operand type(s) for +: 'float' and 'str'
I appreciate all the help I can get. Thanks a lot
我很感激我能得到的所有帮助。非常感谢
采纳答案by Scott Hunter
Since score
was created by splitting a string, it's elements are all strings; hence the complaint about trying to add a float to a string. If you want the value that that string represents, you need to compute that; something like float(score[i])
.
由于score
是通过拆分字符串创建的,所以它的元素都是字符串;因此,关于尝试向字符串添加浮点数的抱怨。如果您想要该字符串表示的值,则需要计算它;类似的东西float(score[i])
。
回答by ForceBru
score
is a list of strings, so you definitely cannot add a string to a float as you do here: addedScore = addedScore + score[i]
. You have to convert this string to a float: addedScore = addedScore + float(score[i])
score
是一个字符串列表,因此您绝对不能像此处那样将字符串添加到浮点数:addedScore = addedScore + score[i]
。您必须将此字符串转换为浮点数:addedScore = addedScore + float(score[i])
回答by zondo
When you split the contents of the file, they are still strings. Change score = score_file.read().split(' ')
to score = [float(x) for x in score_file.read().split(" ")]
. You probably don't need to do .split(" ")
, because str.split()
will by default split by whitespace. Therefore, you can use .split()
.
当您拆分文件的内容时,它们仍然是字符串。更改score = score_file.read().split(' ')
为score = [float(x) for x in score_file.read().split(" ")]
。你可能不需要做.split(" ")
,因为str.split()
默认情况下会被空格分割。因此,您可以使用.split()
.