Ama*_*nda 7 python dictionary integer
我有一本字典。键是单词,值是这些单词出现的次数。
countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
Run Code Online (Sandbox Code Playgroud)
我想找出有多少元素出现的值大于 1、值大于 20 和值大于 50。
我找到了这个代码
a = sum(1 for i in countDict if countDict.values() >= 2)
Run Code Online (Sandbox Code Playgroud)
但我得到一个错误,我猜这意味着字典中的值不能作为整数处理。
builtin.TypeError: unorderable types: dict_values() >= int()
Run Code Online (Sandbox Code Playgroud)
我尝试修改上面的代码使字典值为整数,但这也不起作用。
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'
Run Code Online (Sandbox Code Playgroud)
有什么建议?
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']
Run Code Online (Sandbox Code Playgroud)
如果您只想要字数,请使用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
Run Code Online (Sandbox Code Playgroud)
请注意,Python 变量使用小写和下划线(蛇形大小写):count_dict而不是countDict. 按照惯例,驼峰案例用于 Python 中的类:
>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
>>> [word for word, occurrences in countDict.items() if occurrences >= 20]
['who', 'joey']
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅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})
Run Code Online (Sandbox Code Playgroud)
当然,如果您想要不同的结果,您可以更改返回值或阈值。
但你实际上非常接近,你可能只是混淆了语法 - 正确的是:
a = sum(1 for i in countDict.values() if i >= 2)
Run Code Online (Sandbox Code Playgroud)
因为您想要迭代values()并检查每个值的条件。
你得到的是一个例外,因为之间的比较
>>> countDict.values()
dict_values([2, 409, 2, 41, 2])
Run Code Online (Sandbox Code Playgroud)
像这样的整数2没有任何意义。