/' str'的类型错误不支持的操作数类型和' int'

时间:2015-07-30 15:49:23

标签: python

我试图从列表中找到三个数字的平均分数,如下所示:

a = (lines.split(":")[1].split(",")[-3:])
Print (a)
Averagescore = sum(a)/len(a)
Print (averagescore)

然后它说: /' str'的类型错误不支持的操作数类型和' int'

1 个答案:

答案 0 :(得分:1)

我怀疑您描述的错误消息可能对此代码不准确,但问题是您尝试将字符串列表视为整数列表。例如

>>> 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