
[英]TypeError:unsupported operand type(s) for -: 'str' and 'int'
[英]typeerror unsupported operand type(s) for / 'str' and 'int'
如果三个数字,我试图从列表中找到平均分数,如下所示:
a = (lines.split(":")[1].split(",")[-3:])
Print (a)
Averagescore = sum(a)/len(a)
Print (averagescore)
然后它说: typeerror unsupported operand type(s) for / 'str' and 'int'
我怀疑您描述的错误消息对于此代码可能不准确,但问题是您试图将字符串列表视为整数列表。 例如
>>> s = "1 16 32" # string
>>> s.split() # this returns a list of strings
['1', '16', '32']
>>> s.split()[0] + 1 # you can't add an int to a string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
如果要将它们视为整数(或浮点数),则需要将转换添加为
a = [int(n) for n in s.split()]
a = [float(n) for n in s.split()] # alternatively
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.