【问题标题】:How to add scores from external file into a dictionary and rank them from 1 to 10如何将外部文件中的分数添加到字典中并将它们从 1 到 10 排名
【发布时间】:2020-01-31 00:54:27
【问题描述】:

我正在为学校做 Python 掷骰子游戏,但遇到了文件和字典问题。我有一个包含 10 个分数和 10 个名称的文件,分别相邻,可以让它引入 10 个现有的,并对它们进行排序,但无法获取新的分数和名称。

尝试使用dict.update() 更新字典,但它会抛出一个 TypeError: '<' not supported between instances of 'str' and 'int':

highScores = {}

with open("highscores.txt") as f:
    for line in f:
        (key, val) = line.split()
        highScores[int(key)] = val

for k, v in sorted(highScores.items()):
    print(k,v)
score = input("S: ")
user = input("N: ")
winner = {score:user}
highScores.update(winner)

for k, v in sorted(highScores.items()):
    print(k,v)

【问题讨论】:

  • highscores.txt 中有什么内容?不是描述;实际数据。

标签: python python-3.x file dictionary


【解决方案1】:

根据您的代码,我想highscores.txt 看起来像

100 user1
90 user2
95 user3
...

由于input(__prompt: Any) -> str 返回类型str,您必须更改您的winner 字典以包含带有int 类型键的ak,v-pair(就像您在highScores[int(key)] = val 中所做的那样):

winner = {int(score) : user}

错误告诉您strint 无法与> 运算符进行比较。看看builtins.pyi中比较运算符的实现:

class int:
    def __gt__(self, x: int) -> bool: ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多