【发布时间】:2016-12-02 05:03:29
【问题描述】:
我正在为性能很重要的应用程序编写代码。我想知道为什么defaultdict 似乎比setdefault 更快。
我希望能够使用setdefault,主要是因为我不喜欢嵌套defaultdict 的打印输出(参见下面的实现)。
在我的代码中,我需要测试element_id 是否已经是字典的键。
这是我正在测试的两个函数:
def defaultdictfunc(subcases,other_ids,element_ids):
dict_name= defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
for subcase in subcases:
for other_id in other_ids:
for element_id in element_ids:
if element_id in dict_name[subcase][other_id]:
# error duplicate element_id
pass
else:
dict_name[subcase][other_id][element_id]=0
return dict_name
def setdefaultfunc(subcases,other_ids,element_ids):
dict_name={}
for subcase in subcases:
for other_id in other_ids:
for element_id in element_ids:
if element_id in dict_name.setdefault(subcase,{}).setdefault(other_id,{}):
# error duplicate element_id
pass
else:
dict_name[subcase][other_id][element_id]=0
return dict_name
IPython 输入输出:
In [1]: from numpy.random import randint
In [2]: subcases,other_ids,element_ids=(randint(0,100,100),randint(0,100,100),randint(0,100,100))
In [5]: from collections import defaultdict
In [6]: defaultdictfunc(subcases,other_ids,element_ids)==setdefaultfunc(subcases,other_ids,element_ids)
Out[6]: True
In [7]: %timeit defaultdictfunc(subcases,other_ids,element_ids)
10 loops, best of 3: 177 ms per loop
In [8]: % timeit setdefaultfunc(subcases,other_ids,element_ids)
1 loops, best of 3: 351 ms per loop
为什么setdefaultfunc 更慢。我认为底层代码是一样的。有没有办法提高它的速度?
谢谢
【问题讨论】:
-
The docs,一定要说,“[使用
defaultdict] 比使用dict.setdefault()的等效技术更简单、更快。”要解决打印问题,使用dict(dict_name)将defaultdict转换回常规dict很容易(且快速)。 -
defaultdict比dict.setdefault()更快是有道理的,因为前者在创建时为整个 dict 设置默认值,而setdefault()在读取时为每个元素执行它。使用setdefault的一个原因是当您分配的默认值是基于键(或其他东西)而不是整个字典的通用默认值时。 -
谢谢大家,现在很有意义。
标签: python dictionary defaultdict setdefault