Python 3.6.5如何显示带有名称的文件中的前5名分数



如何在外部文本文件中显示前5名的分数和玩家名称,该文件如下所示:

Fred's score: 12
Bob's score: 14
Amy's score: 17
Adam's score: 11
Caitlin's score: 13 
tom's score: 19

我写了这个代码来存储分数:

from random import randint
score1 = randint(1,20)
score2 = randint(1,20)
user1 = (input("What is your name? "))
user2 = (input("What is your name? "))
if score1 > score2:
f = open("test.txt","a")
f.write("n")
f.write(user1)
f.write(" 's score: ")
f.write(str(score1))
f.close()
if score1 < score2:
f = open("test.txt","a")
f.write("n")
f.write(user2)
f.write(" ,s score: ")
f.write(str(score2))
f.close()

使用字典保存名称和相关分数可能是最简单的。如果文件的内容总是<name>'s score: <value>,那么这应该有效:

d = {}  # dictionary to hold the data
with open('test.txt', 'r') as f: # open and
for line in f.readlines():   # read file lines
# assign the name as key to the score's value
d[line.split("'")[0].strip()] = int(line.split(':')[1].strip())
# sort the list and slice the top 5 
print(sorted(d.items(), key=lambda x: x[1])[::-1])[:5]

应该给你一个前5名的列表及其相关名称:

[('tom', 19), ('Amy', 17), ('Bob', 14), ('Caitlin', 13), ('Fred', 12)]

我只需要阅读整个文件,解析出分数,排序,然后取前5名。
类似这样的东西:

file_path = "/path/to/file.txt"
with open(file_path, 'r') as f:
file_lines = f.readlines()
names_and_scores = [(l.strip().split(' ')[0], float(l.strip().split(' ')[2])) for l in file_lines]
names_and_scores.sort(key=lambda x: x[1], reverse=True)
print(names_and_scores[:5])

这对你有用吗
祝你好运!

这里有一个直接的方法:

with open('file.csv', 'r') as score_file:
scores = [ line.strip().split(' ') for line in score_file ]
scores.sort(key=lambda x: x[2], reverse=True)
for i in range(5):
if i == len(scores):
break
print(' '.join(scores[i]))

如果将分数文件提取到字典中,这可能是另一种解决方案:

scores  = {}  
with open('score_file.txt', 'r') as fs: # open and
for line in fs.readlines():   #read file all lines
scores[int(line.split(':')[1].strip())] = line.split("'")[0].strip()
#scores = {12:'Fred',14:'Bob',17:'Amy',11:'Adam',13:'Caitlin',19:'tom', 10:'x'}
Tops = {}
for i in range(5):
Tops[scores[max(scores.keys())]]= max(scores.keys())
del scores[max(scores.keys())]
print Tops

你应该有:

{'Amy': 17, 'Fred': 12, 'Bob': 14, 'Caitlin': 13, 'tom': 19}

相关内容

最新更新