打印最高平均值 - "不支持的操作数类型为+:' int'和' str'"

时间:2015-02-10 11:38:25

标签: python sorting dictionary

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

1 个答案:

答案 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())