列表理解中的缓存变量

Cache variable in list comprehension

假设我有一个昂贵的操作 expensive(x: int) -> int 和以下列表理解:

# expensive(x: int) -> int
# check(x: int) -> bool
[expensive(i) for i in range(LARGE_NUMBER) if check(expensive(i))]

如果我想为每个 i 避免两次 运行 expensive(i),有什么方法可以通过列表理解来保存它的价值?

使用海象:

[cache for i in range(LARGE_NUMBER) if check(cache := expensive(i))]

您可以模拟嵌套理解:

 [val for i in range(LARGE_NUMBER) for val in [expensive(i)] if check(val)]