[英]Python: Weird result while indexing the dictionary from collections.Counter
假设我有一个数字列表
numbers = ['3', '3', '4', '4']
我想统计列表中元素出现的次数,所以我使用collections.Counter
from collections import Counter
result = Counter(numbers)
result
Counter({'3': 2, '4': 2})
这是我觉得很有趣的事情,如果您尝试索引计数器,无论您放入多少索引,它都会始终显示 0。
result[0]
Out[22]: 0
result[1]
Out[23]: 0
result[100]
Out[24]: 0
result[10000000000]
Out[26]: 0
知道这个有趣的结果吗?
是的,计数器 collections 继承自 dict 并实现了缺少的方法
部分计数器代码
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
'''
def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0
dict 类型将始终尝试调用missing 。 如果计数器总是返回0
请参阅dict
文档:
d[key]
使用键key返回d的项目。 如果密钥不在 map 中,则引发KeyError
。如果 dict 的子类定义了方法
__missing__()
并且key不存在,则d[key]
操作以 key key作为参数调用该方法。 然后d[key]
操作返回或引发__missing__(key)
调用返回或引发的任何内容。 没有其他操作或方法调用__missing__()
。
当你这样做
result[10000000000]
>>> 0
您没有为计数器编制索引,而是在密钥不存在时访问密钥,该密钥的计数为 0
result["a"]
>>> 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.