我的主要课程是问答;一个游戏,最后我想把玩家的名字和分数写进一个文件,然后把文件中的最高分数显示给用户
文件写入部分如下所示
def scores():
#This is where all the scores are written
file = open("test.txt", "w")
file.write("Mary 200")
file.write("\nJohn 500")
file.write("\nAlex 300")
file.close()
#The content is now read from the file and split line by line
file = open("test.txt", "r")
content = file.read()
content = content.split("\n").
scoresList = []
for i in content:
name, score = i.split(" ")
scoresList.append(eval(score))
maxscore = max(scoresList)
现在我有了文件中的最大分数,但是如何将其与“John”匹配,以便同时显示分数和名称
最简单的方法是使用列表。包含元组的列表使用元组中的第一个元素自动排序。所以,把最后几行改成:
注意:我不记得它的排序顺序,您可能需要将
reverse=True
添加到sort()
参数中不要使用
eval()
而不是这样:
执行以下操作:
这将创建以下形式的词典:
现在可以按排序方式显示:
从最低到最高打印姓名和分数:
如果要按降序列出,请为排序函数指定
sorted(content, key=content.get, reverse=True)
相关问题 更多 >
编程相关推荐