打印最高平均值 - "unsupported operand type(s) for +: 'int' and 'str'"

Printing highest average - "unsupported operand type(s) for +: 'int' and 'str'"

我正在尝试实现从最高到最低打印的平均分数的输出。但是,当我 运行 程序时,我得到一个错误: 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'

您的字典中有 字符串 ,但 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())