【发布时间】:2018-09-04 21:34:56
【问题描述】:
我们知道,在 Python 3.6 字典中,插入排序作为实现细节,在 3.7 中可以依赖插入排序。
我预计dict 的子类也会出现这种情况,例如collections.Counter 和collections.defaultdict。但这似乎只适用于defaultdict 案例。
所以我的问题是:
- 是否确实为
defaultdict维护了排序,但为Counter维护了排序?如果有,是否有简单的解释? - 是否应该将
collections模块中的这些dict子类的排序视为实现细节?或者,例如,我们能否依靠defaultdict像 Python 3.7+ 中的dict那样被插入排序?
这是我的基本测试:
字典:有序
words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
dict_counter = {}
for w in words:
dict_counter[w] = dict_counter.get(w, 0)+1
print(dict_counter)
# {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}
计数器:无序
from collections import Counter, defaultdict
print(Counter(words))
# Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
defaultdict:有序
dict_dd = defaultdict(int)
for w in words:
dict_dd[w] += 1
print(dict_dd)
# defaultdict(<class 'int'>, {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2})
【问题讨论】:
标签: python python-3.x dictionary counter defaultdict