【问题标题】:Python - Sort list in descending order - Type ErrorPython - 按降序排序列表 - 类型错误
【发布时间】:2019-09-28 21:25:39
【问题描述】:

iPod Game Guesser - 排行榜功能

    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]}')\\,它显示的错误如下:

TypeError:字符串索引必须是整数

请帮忙!任何 cmets 将不胜感激!

【问题讨论】:

  • 播放器1:9播放器2:6播放器3:7播放器4:8
  • 这是原始数据的样子(在 .txt 文件中)
  • 您的意思是写{scores[user]} 而不是{score[user]}?请注意,您同时拥有 score 和 scores 作为变量名。
  • 哦,我刚刚把 print (f'{user} : {score[user]}') 改成了:
  • print (f'{user} : {scores[user]}') 现在它可以工作了,看起来我在打字时犯了一个愚蠢的错误,非常感谢你发现它!

标签: python-3.x sorting


【解决方案1】:

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

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]))

【讨论】:

  • 感谢您的帮助,但目标是从外部文件中提取列表并对其进行排序。还有其他方法可以实现吗?
  • 目前有什么问题?
  • 我明白你的意思了,现在我只需要缩进代码。抱歉回复晚了
  • 我成功运行了你发给我的代码,它显示排行榜但不是按分数降序排列。
  • 我已经修改了您上面的评论,它解决了我的问题,非常感谢您的帮助!
猜你喜欢
  • 2011-05-10
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 2013-06-17
相关资源
最近更新 更多