
[英]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.