gpt4 book ai didi

python - setdefault 与 defaultdict 性能

转载 作者:太空狗 更新时间:2023-10-29 21:10:48 27 4
gpt4 key购买 nike

我正在为性能很重要的应用程序编写代码。我想知道为什么 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 比较慢。我认为底层代码是一样的。有没有办法提高它的速度?

谢谢

最佳答案

根据用户aneroid :

It would make sense that defaultdict is faster that dict.setdefault() since the former sets its default for the entire dict at creation time, whereas setdefault() does it per element when it is read. One reason to use setdefault is when the default you assign is based on the key (or something) rather than a generic default for the entire dict.

关于python - setdefault 与 defaultdict 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com