gpt4 book ai didi

python - 字典值的惰性评估?

转载 作者:行者123 更新时间:2023-12-02 16:03:48 26 4
gpt4 key购买 nike

假设我有以下字典 d={'a': heavy_expression1, 'b': heavy_expression2}

我如何包装表达式,以便在访问它们时对其进行求值,之后不执行求值?

d['a'] # only here heavy_expression1 is executed
d['a'] # no execution here, already calculated

我需要使用 lambda 还是生成器?

最佳答案

带有 lambda 的版本:

class LazyDict(dict):
def __init__(self, lazies):
self.lazies = lazies
def __missing__(self, key):
value = self[key] = self.lazies[key]()
return value

d = LazyDict({'a': lambda: print('heavy_expression1') or 1,
'b': lambda: print('heavy_expression2') or 2})
print(d['a'])
print(d['a'])
print(d['b'])
print(d['b'])

输出:

heavy_expression1
1
1
heavy_expression2
2
2

关于python - 字典值的惰性评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69947671/

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