为什么总是计算默认值?

2024-05-15 16:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字典d,它有一个键0或键1。我想给x赋值d[0](如果存在),否则赋值d[1]。如果密钥0存在,我还想销毁它。我会写:

    x = d.pop(0,d[1])

但是为d = {0:'a'}运行这个会产生一个错误。你知道吗

类似地,假设我有一个接受关键字参数x的函数。如果已经计算了x,那么我想使用给定的值。否则,我需要计算它。你知道吗

    import time
    def long_calculation():
        time.sleep(10)
        return 'waited'

    def func(**kwargs):
        x = kwargs.pop('x',long_calculation())
        return x

运行f(x='test')需要10秒。你知道吗

我可以这样做

    x = kwargs.pop('x',None)
    if x is None:
        x = long_calculation()

但这有点麻烦。你知道吗


Tags: none参数return字典timedef错误密钥
1条回答
网友
1楼 · 发布于 2024-05-15 16:42:46

对于缓存函数结果,请查看^{}。示例:

from functools import lru_cache
@lru_cache(maxsize=32)
def long_calculation():
    time.sleep(10)
    return 'waited'

第二个调用返回缓存的值:

print(long_calculation()) # 10 seconds
print(long_calculation()) # instant

如果你只是想短路dict.pop(),我认为把它放在嵌套的try块中更简单。比如:

try: 
    d.pop(0)
except KeyError:
    try:
        d[1]
    except KeyError:
        <expensive value>

相关问题 更多 >