我正试图写一个软件,总结从第三方文本文件的点。这是文本文件的外观:
essi 5
pietari 9
essi 2
pietari 10
pietari 7
aps 25
essi 1
主要功能是将每个玩家的得分总和返回到一个列表中,玩家按字母顺序排列。我已经做了所有的事情,除了能够计算数字的总和,它给了我文本文件中埃西和皮埃塔里的最后一个数字。这是我的密码:
def main():
filename = input("Enter the name of the score file: ")
read_file = open(filename, mode="r")
score = {}
for line in read_file:
line = line.rstrip()
name, points = line.split(" ")
score[name] = points
print("Contestant score:")
for key in sorted(score):
print(key,score[key])
if __name__ == "__main__":
main()
它给出了:
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 1
pietari 7
Process finished with exit code 0
所以基本上我需要的结果是:
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 8
pietari 26
Process finished with exit code 0
请尝试使用以下内容定义词典:
然后将更新更改为
您可以使用
collections
中的Counter
来简化这一点请记住,您还需要将字符串转换为整数:
int(points)
在代码中,您并没有将计数添加到的“score”字典中,只使用文件中的最后一个值重写分数
印刷品:
相关问题 更多 >
编程相关推荐