如何在 if 语句中正确使用赋值运算符和 mod 运算符?

How to properly use assignment operator with mod operator in an if statement?

我正在尝试在 python 中使用 Walrus 运算符和不同的 if 语句,我试图替换的代码如下所示:

from time import time

n = 10
numbers = []
results = []

def calculate(x):
    return x ** 2 + 5

t1 = time()
results= [calculate(i) for i in range(n) if (calculate(i)%2) == 0]
t2 = time()
print(f"it took: {t2 - t1} seconds to execute without walrus!")
print(results)

预期的输出应该是这样的:

it took: 2.5987625122070312e-05 seconds to execute without walrus!
[6, 14, 30, 54, 86]

现在,如果尝试用海象运算符(概念)替换我的代码,如果我尝试以下操作,它确实会在结果中给出 True 或 0:

t1 = time()
results= [result for i in range(n) if (result:= calculate(i) %2  == 0) ]
t2 = time()
print(f"it took: {t2 - t1} seconds to execute with walrus!")
print(results)

输出:

it took: 2.1219253540039062e-05 seconds to execute with walrus!
[True, True, True, True, True]

或:

t1 = time()
results= [result for i in range(n) if ((result:= calculate(i) %2)  == 0) ]
t2 = time()
print(f"it took: {t2 - t1} seconds to execute with walrus!")
print(results)

输出:

it took: 2.0742416381835938e-05 seconds to execute with walrus!
[0, 0, 0, 0, 0]

现在我知道 if 语句中的逻辑是错误的,如果我不使用理解,这可能会按预期工作,但有什么办法可以让它像这样工作吗?

您捕获的是比较结果(因此是布尔值),而不是 calculate.

的结果

你应该这样做:

results = [result for i in range(n) if (result:= calculate(i)) %2  == 0 ]