【问题标题】:How can I use a comparison operator to filter integers in a dictionary that also includes strings as values?如何使用比较运算符过滤还包含字符串作为值的字典中的整数?
【发布时间】:2020-05-15 14:29:18
【问题描述】:

我想编写一个代码来消除超过某个阈值的 int 值,同时忽略字符串。目前我的代码抛出错误'>' not supported between instances of 'str' and 'int'。代码如下:

dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 'montana' }
number = 2

def remove_numbers_larger_than(number, dictionary):
    for k, v in list(dictionary.items()):
        if v > number: 
            del dictionary[k]
return dictionary 



print(remove_numbers_larger_than(number, dictionary))

输出应该是:{'a': 1, 'b': 2, 'e': 'montana'}

【问题讨论】:

  • if type(v) is int and v > number:

标签: python dictionary iteration


【解决方案1】:

您可以使用try-except 或检查int 类型:

# try-except
def remove_numbers_larger_than(number, dictionary):
    for k, v in list(dictionary.items()):
        try:
            if v > number: 
                del dictionary[k]
        except TypeError:
            pass
    return dictionary 

# Check type
def remove_numbers_larger_than(number, dictionary):
    for k, v in list(dictionary.items()):
        if isinstance(v, int) and v > number: 
            del dictionary[k]
    return dictionary 

函数可以进一步简化为字典推导:

def remove_numbers_larger_than(number, dictionary):
    return {k: v for k,v in dictionary.items() if not(isinstance(v, int) and v > number)}

【讨论】:

    【解决方案2】:

    使用字典理解:

    dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 'montana' }
    number = 2
    print({k: v for k, v in dictionary.items() if not isinstance(v, int) or v <= number})
    

    输出:

    {'a': 1, 'b': 2, 'e': 'montana'}
    

    【讨论】:

      【解决方案3】:

      这可以帮助你:

      dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 'montana' }
      number = 2
      
      newd = {k:v for k,v in dictionary.items() if type(v) != int or v <= number}
      print(newd)
      # {'a': 1, 'b': 2, 'e': 'montana'}
      

      【讨论】:

      • 您应该使用isinstance 而不是type(v) != int。后者将为子类返回False,但它们是有效的int 实例。
      猜你喜欢
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2017-03-28
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2021-03-03
      相关资源
      最近更新 更多