我试图获得从最高到最低打印的平均分数的输出。但是,当我运行程序时,出现错误:unsupported operand type(s) for +: 'int' and 'str'
。
我是Python的新手,我不知道这个代码出了什么问题:
f = open('ClassA.txt', 'r')
#a empty dictionar created
d = {}
#loop to split the data in the ext file
for line in f:
columns = line.split(": ")
#identifies the key and value with either 0 or 1
names = columns[0]
scores = columns[1].strip()
#appends values if a key already exists
tries = 0
while tries < 3:
d.setdefault(names, []).append(scores)
tries = tries + 1
if wish == '3':
for names, v in sorted(d.items()):
average = sum(v)/len(v)
print ("{} Scored: {}".format(names,average))
我得到的错误:
Traceback (most recent call last):
File "N:\task 3 final.py", line 33, in <module>
average = sum(v)/len(v)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
答案 0 :(得分:1)
您的字典中有字符串,但sum()
将以数字0
开头,仅对数字值求和:
>>> sum(['1', '2'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
根据您的格式,将您的得分转换为数字int()
或float()
:
scores = int(columns[1].strip())