仅显示 .txt 文件中某人的最高分 (Python 3)

Displaying only a person's highest score from a .txt file (Python 3)

我正在尝试学习使用 Python 进行个人项目的基础知识。

我创建了一个程序,询问用户十个地理问题,然后将他们的分数保存到 .txt 文件中,格式如下:

Imran - 8
Joeseph - 5
Test1 - 6
Test2 - 4
Joeseph - 10
Aaron - 4
Test1 - 1
Zzron - 1
Joeseph - 3
Test1 - 10
Joeseph - 4

我现在正尝试制作另一个程序来读取此 .txt 文件,并按字母顺序显示每个人的最高分,如下所示:

Aaron - 4
Imran - 8
Joeseph - 10
Test1 - 10
Test1 - 6
Test2 - 4
Zzron - 1

我目前已经能够按字母顺序组织用户的分数,但是我如何更改代码以便只显示一个人的最高分数?:

with open("highscores.txt", "r+")as file:
    file.seek(0)
    scores = file.readlines()

alphabetical = []
for i in range (0, len(scores)):
    line = scores[i].rstrip('\n')
    alphabetical.append(line)

alphabetical = sorted(alphabetical)
for i in range (0, len(alphabetical)):
    print (alphabetical[i])

您需要使用字典来存储您的分数;分别存储名称和分数(分数转换为整数),仅在分数较高时才替换分数:

user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score

建立字典后,您可以对键(名称)进行排序并显示具有该分数的每个名称:

for name in sorted(user_scores):
    print(name, '-', user_scores[name])

演示:

>>> scores = '''\
... Imran - 8
... Joeseph - 5
... Test1 - 6
... Test2 - 4
... Joeseph - 10
... Aaron - 4
... Test1 - 1
... Zzron - 1
... Joeseph - 3
... Test1 - 10
... Joeseph - 4
... '''.splitlines(True)
>>> user_scores = {}
>>> for line in scores:
...     name, score = line.rstrip('\n').split(' - ')
...     score = int(score)
...     if name not in user_scores or user_scores[name] < score:
...         user_scores[name] = score
... 
>>> for name in sorted(user_scores):
...     print(name, '-', user_scores[name])
... 
Aaron - 4
Imran - 8
Joeseph - 10
Test1 - 10
Test2 - 4
Zzron - 1
with open ("input.txt", "r") as myfile:
    data = myfile.read()

rows = data.split("\n")
people = {}
for row in rows:
  tmp = row.split(" - ")
  if len(tmp) < 2: continue
  if tmp[0] not in people: people[tmp[0]] = []
  people[tmp[0]].append(int(tmp[1]))

for person in people:
  print person, max(people[person])