Python如何将新值与现有值相加?

MT2*_*247 3 python

文本文件包含:

Matt 25
Matt 22
John 1
John 2
John 5
Run Code Online (Sandbox Code Playgroud)

我试图用这个计算他们的总分,但现在它只是将数字加到值上,而不是求和:

filename = input("Enter the name of the score file: ")

file = open(filename, mode="r")
print("Contestant score:")

score = dict()

for file_line in sorted(file):

    file_line = file_line.split()
    if file_line[0] in score:
        score[file_line[0]] += file_line[1]
    else:
        score[file_line[0]] = file_line[1]

print(score)

file.close()
Run Code Online (Sandbox Code Playgroud)

但打印是: {'Matt': '2525', 'John': '125'}

而不是:{'马特':'50','约翰':'8'}

Abh*_*hur 7

将其更改为

    if file_line[0] in score:
        score[file_line[0]] += int(file_line[1])
    else:
        score[file_line[0]] = int(file_line[1])
Run Code Online (Sandbox Code Playgroud)

file_line[1]是一个字符串,所以使用+=运算符只是附加到字符串而不是执行数学加法。