我看到其他Python程序员在以下情况下使用collections模块中的defaultdict:
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
def main():
d = defaultdict(list)
for k, v in s:
d[k].append(v)
我通常使用setdefault方法来解决这个问题:
def main():
d = {}
for k, v in s:
d.setdefault(k, []).append(v)
文档确实声称使用defaultdict更快, 但是在我自己测试时,我发现相反的情况:
$ python -mtimeit -s "from withsetdefault import main; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)];" "main()"
100000 loops, best of 3: 4.51 usec per loop
$ python -mtimeit -s "from withdefaultdict import main; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)];" "main()"
100000 loops, best of 3: 5.38 usec per loop
我设置的测试有问题吗?
参考资料,我正在使用Python 2.7.3 [GCC 4.2.1(Apple Inc. build 5666)
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
,而另一个文件没有? - Claudiuwithsetdefault.py
和withdefaultdict.py
里面有什么。如果其中一个包含那行代码而另一个没有,那就可以解释这个差异了。 - Claudiu