1

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

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

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

4

2 回答 2

4

使用海象:

[cache for i in range(LARGE_NUMBER) if check(cache := expensive(i))]
于 2020-02-06T02:04:19.340 回答
0

您可以模拟嵌套理解:

 [val for i in range(LARGE_NUMBER) for val in [expensive(i)] if check(val)]
于 2020-02-06T22:10:00.970 回答