外部文件的内容如下:
Ricky, 12
Sachin, 45
Brian, 2
Monty, 1
我基本上想要做的是能够在python中阅读并能够订购它,所以它在最低分和最高分得分。
这是我到目前为止的代码:
def SaveTopScores():
return HiScores.rsplit('(',1)[1]
with open("HiScores.txt", "r")as file:
HiScoreslist = HiScores.read().splitlines()
HiScoreslist.sort()
HiScoreslist.sort(key=HiScore)
for HiScore in HiScoreslist:
print(HiScore)
我仍然是python的新手,确实需要帮助。请纠正我错误的地方并告诉我,如果我完全错了,如果是这样,那么解决问题的最佳途径是什么?
答案 0 :(得分:2)
有一些列表理解:
with open("HiScores.txt") as hiscores:
scores = [line.split(',') for line in hiscores if line.strip()]
scores = [(name.strip(), int(score)) for name, score in scores]
scores.sort(key=lambda s: s[1], reversed=True)
for name, score in scores:
print('{:<20} {:>10}'.format(name, score))
此:
with ... as ...
)打开,以便自动关闭答案 1 :(得分:1)
那么,有点像这样吗?
def scores(fn):
data = []
with open(fn) as f:
for ln in f:
name, score = ln.strip().split(',')
data.append((int(score.strip()), name))
for score, name in sorted(data, reversed=True):
print name, score
答案 2 :(得分:0)
如果不过多更改原始代码,这应该可行。如果您需要解释任何部分,请告诉我。
with open("HiScores.txt", "r") as fin:
HiScores = fin.read().splitlines()
HiScoresList = []
for score in HiScores:
name, score = score.split(', ')
score = int(score.strip())
HiScoresList.append((name, score))
# Look at two score entries, and compare which score is larger
def BestScore(a, b):
return cmp(b[1], a[1])
HiScoresList.sort(BestScore)
for HiScore in HiScoresList:
print(HiScore)
打印:
('Sachin', 45)
('Ricky', 12)
('Brian', 2)
('Monty', 1)