Python - 按降序对列表进行排序 - 类型错误



iPod 游戏猜测器 - 排行榜功能

leaderboard = open("Score.txt", "a+")
score = str(score)
leaderboard.write(Username + ' : ' + score + 'n')
leaderboard.close()
leaderboard = open("Score.txt", "r")
Scorelist = leaderboard.readlines()
scores = {}
for row in Scorelist:
user, score = row.split(':')
scores[user] = int(score)
highest_ranking_users = sorted(scores, key=lambda x: scores[x], reverse=True)
for user in highest_ranking_users:
print (f'{user} : {score[user]}')

所以这是我为我的GCSE OCR项目做的游戏,不知何故,我在代码的最后一行出现错误。 \\print (f'{user} : {score[user]}'(\\,它显示的错误如下所示:

类型错误:字符串索引必须是整数

请帮忙!任何意见将不胜感激!

您正在使用字典类型,排序是针对列表的,而不是字典。为了对字典进行排序,您必须使用列表并再次制作字典,或者仅使用该列表打印最高分列表。

score = {'Player1' : 9, 'Player2' : 6, 'Player3' : 7, 'Player4' : 8}
sorted_score = sorted(score.items(), key=lambda x: x[1], reverse=True)
for score in sorted_score:
print('{} : {}'.format(score[0], score[1]))

这给出了结果,

Player1 : 9
Player4 : 8
Player3 : 7
Player2 : 6

你可以调整我的代码,即

with open("test.txt", "r") as file:
scores = []
for row in file.read().splitlines():
scores.append(row.split(' : '))
sorted_score = sorted(scores, key=lambda x: x[1], reverse=True)
for score in sorted_score:
print('{} : {}'.format(score[0], score[1]))

最新更新