如何匹配同一文件中的两条信息?

2024-06-16 10:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我的主要课程是问答;一个游戏,最后我想把玩家的名字和分数写进一个文件,然后把文件中的最高分数显示给用户

文件写入部分如下所示

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”匹配,以便同时显示分数和名称


Tags: 文件thetesttxtreadislineopen
2条回答

最简单的方法是使用列表。包含元组的列表使用元组中的第一个元素自动排序。所以,把最后几行改成:

scoresList = []
for i in content:
    name, score = i.split(" ")
    scoresList.append(float(score), name))

scoresList.sort()
maxscore = scoresList[0]

注意:我不记得它的排序顺序,您可能需要将reverse=True添加到sort()参数中

不要使用eval()

而不是这样:

scoresList = []
for i in content:
    name, score = i.split(" ")
    scoresList.append(eval(score))

执行以下操作:

content = {name:int(score) for name, score in (item.split() for item in content)}

这将创建以下形式的词典:

{'Mary': 200, 'Alex': 300, 'John': 500}

现在可以按排序方式显示:

for item in sorted(content, key=content.get):
    print(item, content.get(item))

从最低到最高打印姓名和分数:

Mary 200
Alex 300
John 500

如果要按降序列出,请为排序函数指定sorted(content, key=content.get, reverse=True)

相关问题 更多 >