我正在尝试在 python 中使用具有不同 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 语句中的逻辑是错误的,如果我没有使用理解,这可能会按预期工作,但有什么办法可以让它像这样工作吗?