[英]Fastest way to set a dictionary value in python when greater than current key value
我经常遇到一种情况,即当且仅当新值大于旧值时,才必须将字典键设置为一个值(始终为整数)。 分析揭示了我当前正在执行的方式正在占用某种功能的全部时间的1/3。 这是我目前的操作方式:
some_dict[k] = max(new_val, some_dict.get(k, 0))
有没有更快的方法?
比较我能想到的三种不同方法-
In [12]: def foo():
....: d = {1:2 , 3:4}
....: d[1] = max(3, d.get(1,0))
....:
In [13]: def foo1():
....: d = {1:2, 3:4}
....: if d.get(1,0) < 3:
....: d[1] = 3
....:
In [14]: def foo2():
....: d = {1:2, 3:4}
....: d[1] = 3 if d.get(1,0) < 3 else d.get(1)
....:
In [15]: %timeit foo()
The slowest run took 4.18 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1 µs per loop
In [16]: %timeit foo1()
The slowest run took 11.46 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 564 ns per loop
In [17]: %timeit foo2()
The slowest run took 4.79 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 556 ns per loop
In [18]: %timeit foo()
The slowest run took 10.17 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 861 ns per loop
In [19]: %timeit foo1()
The slowest run took 5.90 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 645 ns per loop
In [20]: %timeit foo2()
The slowest run took 8.01 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 523 ns per loop
如果我们认为%timeit
的结果似乎是最快的-
some_dict[k] = new_val if some_dict.get(k, 0) < new_val else some_dict.get(k)
假定new_val始终大于0,因此在else部分中不需要some_dict.get(k,0)
。 尽管即使没有太大的区别。
好吧,显而易见的另一种方法是不总是执行分配,并且不调用额外的函数调用:
if some_dict.get(k, 0) < new_val:
some_dict[k] = new_val
这实际上是否更快是另一个问题。
还有另一种尚未提及的方法:
get = d.get
val = get(k, 0)
d[k] = (val, new_val)[val<new_val]
此方法仅在内存中播放,根本不使用分支。
有多快? 嗯,应该很快。
get = d.get
将指针保存在字典之外,以便更快地访问该方法。
您也可以使用dict.setdefault()。 这是一个有趣的小方法。
参见help(dict.setdefault)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.