获取python中值大于某个整数的字典键的计数

2024-05-14 19:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

有什么建议吗?


Tags: inforif字典整数单词次数dict
3条回答

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变量使用小写和下划线,而不是camelcase:count_dict,而不是countDict。用这个惯例来避免混淆自己和他人是值得的。有关详细信息,请参见PEP8

您可以使用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这样的整数没有任何意义。

你需要这个:

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

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

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

相关问题 更多 >

    热门问题