python - 高分功能问题

标签 python

我正在尝试为类里面的一个小问答游戏创建一个高分列表。但我遇到了问题,因为我似乎无法获得打印输出,而不仅仅是随机打印字典。这个片段实际上并不是来自完整的程序,因为我不想破坏任何东西,所以它只是尝试推理出该函数。

scores = {'score1': {'initials': 'ywo',
                     'score': 20},
          'score2': {'initials': 'JRV',
                     'score': 18},
          'score3': {'initials': 'blh',
                     'score': 16},
          'score4': {'initials': 'yth',
                     'score': 15},
          'score5': {'initials': 'rtg',
                     'score': 12}}

total_score = 17


#iterates over the scores to see if new score and initials should be input
for i in (scores):
        if total_score > scores[i]['score']:
        scores[i]['initials'] = 'JKE'
        scores[i]['score'] = total_score
        break

#prints scores in a table like format rather than list
print("HIGH\tSCORES")
for i in scores:
    print(scores[i]['initials'], "\t", scores[i]['score'])

我的输出每次都是随机的。我只想按从高到低的顺序打印字典,例如:

ywo    20 
JRV    18 
JKE    17

等等等等

我遇到的另一个问题是,我不确定如何将字典中的其他分数降低。因此,如果 JKE 的分数替换了 blh 的分数,则 blh 不仅会从字典中删除,还会向下移动到 Score4 索引,而 Score4 值将移动到 Score5 等。我感谢任何建议!谢谢你!

最佳答案

我认为你可能想让这有点太复杂(尽管这听起来像家庭作业,所以这可能是一个要求)。

我会像这样处理它:

scores = {'YWO': 20,
          'BLH': 16,
          'YTH': 15,
          'JRV': 18,
          'RTG': 12,
         }


def display_scores(scores):
    for score, name in sorted(((scores[k], k) for k in scores, reverse=True):
        print(name, score)

然后您可以通过以下方式轻松添加球员和分数:

scores[initials] = scores.get(initials, 0) + 1 #or points or whatever

关于python - 高分功能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388553/

相关文章:

python - 在具有最小最近邻距离和最大密度的 3D 空间中随机采样给定点

Python 2.7 + 斯卡比 2.3.1

python - @jupyterlab/vega6-extension 在哪里?

python - Pandas - 通过检查同一数据帧的其他行的条件来派生新列的最佳方法

python - 如何使用 python 日志记录的 SMTPHandler 和 SSL 发送电子邮件

python - python中的if或语句

python - 在 Django 模板中将 user.id 转换为 user.username

python - 如何对多个角色使用 discord.py remove_roles? (作为参数的对象列表)

python - 基于多个列值输出多个文件 pandas python

python - 控制台警告文件