【问题标题】:Looping through dictionary and TypeError: '>=' not supported between instances of 'str' and 'int' - Python遍历字典和 TypeError:'str' 和 'int' 的实例之间不支持'>=' - Python
【发布时间】:2021-07-18 08:34:38
【问题描述】:

我想返回一个用字母等级代替数字等级的新字典

A 为 90,B 为 80,C 为 70,D 为 60。任何低于 60 的都是 F。

例子:

letter_grades({'Bob' : 55, 'Joe' : 90, 'Martha': 86}) 返回 {'Bob' : 'F, 'Joe' : 'A', 'Martha': 'B'}

我写过

def letter_grades(adict):
    """
    Parameter adict: the dictionary of grades
    Precondition: adict is a dictionary with string keys, int values
    """
    for a in adict:
        for i in adict.values():
            if i >= 90:
                adict[a] = 'A'
            elif i >= 80:
                adict[a] = 'B'
            elif i >= 70:
                adict[a] = 'C'
            elif i >= 60:
                adict[a] = 'D'
            elif i < 60:
                adict[a] = 'F'

    return adict

当我输入 letter_grades({'wmw2' : 55, 'abc3' : 90, 'jms45': 86})

我收到一条错误消息:

TypeError:'str' 和 'int' 的实例之间不支持 '>='

谁能告诉我为什么?

【问题讨论】:

    标签: python


    【解决方案1】:

    我会尝试这样的事情。使用 adict.items() 查看键 (k) 和值 (i)。一个好主意是包含一个else,即使它什么都不做(或者您可以在数据错误的情况下引发错误)。

    def letter_grades(adict):
        """
        Parameter adict: the dictionary of grades
        Precondition: adict is a dictionary with string keys, int values
        """
        for k, i in adict.items():
            if i >= 90:
                adict[k] = 'A'
            elif i >= 80:
                adict[k] = 'B'
            elif i >= 70:
                adict[k] = 'C'
            elif i >= 60:
                adict[k] = 'D'
            elif i < 60:
                adict[k] = 'F'
            else:
                pass
    
        return adict
    
    print(letter_grades({'wmw2' : 55, 'abc3' : 90, 'jms45': 86}))
    

    输出: {'wmw2': 'F', 'abc3': 'A', 'jms45': 'B'}

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多