【问题标题】:get a count of dictionary keys with values greater than some integer in python获取值大于python中某个整数的字典键的计数
【发布时间】:2023-03-20 15:47:01
【问题描述】:

我有一本字典。键是单词,值是这些单词出现的次数。

countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}

我想知道有多少元素的值大于 1、大于 20 和大于 50。

我找到了这段代码

a = sum(1 for i in countDict if countDict.values() >= 2)

但我得到一个错误,我猜这意味着字典中的值不能作为整数处理。

builtin.TypeError: unorderable types: dict_values() >= int()

我尝试修改上面的代码以使字典值成为整数,但这也不起作用。

a = sum(1 for i in countDict if int(countDict.values()) >= 2)

builtins.TypeError: int() argument must be a string or a number, not 'dict_values'

有什么建议吗?

【问题讨论】:

  • a = sum(1 for i in countDict.values() if i >= 2) 你需要自己迭代这些值。

标签: python dictionary integer


【解决方案1】:

countDict.items()countDict 中为您提供键值对,因此您可以编写:

>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
>>> [word for word, occurrences in countDict.items() if occurrences >= 20]
['who', 'joey']

如果只需要字数,请使用len

>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
>>> wordlist = [word for word, occurrences in countDict.items() if occurrences >= 20]
>>> len(wordlist)
2

请注意,Python 变量使用小写和下划线(蛇形大小写):count_dict 而不是countDict。按照惯例,python 中的类使用骆驼大小写:

breakfast = SpamEggs()  # breakfast is new instance of class SpamEggs
lunch = spam_eggs()  # call function spam_eggs and store result in lunch
dinner = spam_eggs  # assign value of spam_eggs variable to dinner

更多详情请见PEP8

【讨论】:

    【解决方案2】:

    您可以使用collections.Counter 和“分类函数”一次性获得结果:

    def classify(val):
        res = []
        if val > 1:
            res.append('> 1')
        if val > 20:
            res.append('> 20')
        if val > 50:
            res.append('> 50')
        return res
    
    from collections import Counter
    
    countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
    Counter(classification for val in countDict.values() for classification in classify(val))
    # Counter({'> 1': 5, '> 20': 2, '> 50': 1})
    

    当然,如果您想要不同的结果,您可以更改返回值或阈值。


    但您实际上非常接近,您可能只是混淆了语法 - 正确的是:

    a = sum(1 for i in countDict.values() if i >= 2)
    

    因为您想遍历 values() 并检查每个值的条件。

    你得到的是一个例外,因为之间的比较

    >>> countDict.values()
    dict_values([2, 409, 2, 41, 2])
    

    2 这样的整数没有任何意义。

    【讨论】:

      【解决方案3】:

      你已经很接近了。你只需要记住i 可以通过if 语句访问。我添加了所有三个示例来帮助您入门。此外,values 会创建字典中所有值的列表,这不是您想要的,而是需要当前评估的值 i

      moreThan2 = sum(1 for i in countDict if countDict[i] >= 2)
      moreThan20 = sum(1 for i in countDict if countDict[i] >= 20)
      moreThan50 = sum(1 for i in countDict if countDict[i] >= 50)
      

      【讨论】:

        【解决方案4】:

        在应用歧视逻辑之前尝试使用 .items()。

        在-

        for key, value in countDict.items():
          if value == 2: #edit for use
             print key
        

        出来-

        house
        boy
        girl
        

        【讨论】:

          【解决方案5】:

          你需要这个:

          >>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
          
          >>> sum(1 for i in countDict.values() if i >= 2)
          5
          

          values() 返回给定字典中所有可用值的列表,这意味着您无法将列表转换为整数。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-01-13
            • 2021-09-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多