简体   繁体   English

得到一个字典键的计数,其值大于python中的某个整数

[英]get a count of dictionary keys with values greater than some integer in python

I have a dictionary. 我有一本字典。 The keys are words the value is the number of times those words occur. 键是单词,值是这些单词出现的次数。

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

I'd like to find out how many elements occur with a value of more than 1, with a value of more than 20 and with a value of more than 50. 我想知道有多少元素出现的值大于1,值大于20且值大于50。

I found this code 我找到了这段代码

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

but I get an error that I'm guessing means that values in dictionaries can't be processed as integers. 但是我得到一个我猜的错误意味着字典中的值不能作为整数处理。

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

I tried modifying the above code to make the dictionary value be an integer but that did not work either. 我尝试修改上面的代码,使字典值为整数但不起作用。

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'

Any suggestions? 有什么建议么?

You need this: 你需要这个:

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

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

values() returns a list of all the values available in a given dictionary which means you can't convert the list to integer. values()返回给定字典中可用的所有值的列表 ,这意味着您无法将列表转换为整数。

You could use collections.Counter and a "classification function" to get the result in one-pass: 您可以使用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})

Of course you can alter the return values or thresholds in case you want a different result. 当然,如果您想要不同的结果,可以更改返回值或阈值。


But you were actually pretty close, you probably just mixed up the syntax - correct would be: 但你实际上非常接近,你可能只是混淆了语法 - 正确的是:

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

because you want to iterate over the values() and check the condition for each value. 因为你想迭代values()并检查每个值的条件。

What you got was an exception because the comparison between 你得到的是一个例外,因为它之间的比较

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

and an integer like 2 doesn't make any sense. 2这样的整数没有任何意义。

countDict.items() gives you key-value pairs in countDict so you can write: 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']

If you just want the number of words, use len : 如果你只想要单词数,请使用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

Note that Python variables use lowercase and underscores rather than camelcase: count_dict rather than countDict . 请注意,Python变量使用小写和下划线而不是camelcase: count_dict而不是countDict It's worth using this convention to avoid confusing yourself and others. 值得使用此约定以避免让自己和他人混淆。 See PEP8 for more details. 有关详细信息,请参阅PEP8

You're quite close. 你很亲密 You just need to remember that i is accessible via the if statement. 你只需要记住i可以通过if语句访问。 I added all three examples to get you started. 我添加了所有三个示例来帮助您入门。 Additionally, values creates a list of all values in the dictionary, which is not what you want, you instead want the currently evaluated value, i . 此外, 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)

Try using .items() before applying your discrimination logic. 在应用鉴别逻辑之前尝试使用.items()。

in - 在 -

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

out - 出 -

house
boy
girl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM