gpt4 book ai didi

python - 当大于当前键值时在 python 中设置字典值的最快方法

转载 作者:行者123 更新时间:2023-11-28 21:50:46 24 4
gpt4 key购买 nike

当且仅当新值大于旧值时,我经常遇到必须将字典键设置为值(始终为整数)的情况。分析表明我目前正在做的事情占用了某个功能的全部 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)。尽管即使这样也没有太大区别。

关于python - 当大于当前键值时在 python 中设置字典值的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446413/

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