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

时间:2015-02-28 17:42:19

标签: python file-io

我正在尝试学习将Python用于个人项目的基础知识。

我创建了一个程序,向用户询问了10个地理问题,然后将其分数保存为.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])

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:-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])