如何在Python列表推导式的if条件中正确结合海象运算符与取模运算符?
Got it, let's sort out your walrus operator issue here! The core problem with your two attempts is that you're capturing the wrong value in result—either a boolean or a remainder—instead of the actual calculated value from calculate(i) that you want to keep in your list.
The Correct Approach
We need to use the walrus operator to store the full result of calculate(i) first, then check if that value is even, and finally include that stored value in the list when the condition passes. Here's how to do it right:
from time import time n = 10 numbers = [] results = [] def calculate(x): return x ** 2 + 5 t1 = time() # Corrected list comprehension with proper walrus usage 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)
Why This Works
(result := calculate(i))evaluatescalculate(i)once, assigns that full value toresult, and returns the value itself.- We then check if
result % 2 == 0(i.e., if the calculated value is even). - When the condition is true,
result(the actual calculated number) is added to the list—exactly what we want!
What Went Wrong With Your Attempts
Let's break down why your previous tries gave unexpected outputs:
写法一:
results= [result for i in range(n) if (result:= calculate(i) %2 == 0) ]Here, you're assigning the boolean result of
calculate(i) %2 == 0toresult. So every time the condition passes, you're addingTrueto the list instead of the calculated number.写法二:
results= [result for i in range(n) if ((result:= calculate(i) %2) == 0) ]This time, you're assigning the remainder of
calculate(i) % 2toresult. When the condition passes, that remainder is0, so your list fills up with zeros instead of the actual calculated values.
Expected Output
Running the corrected code will give you the same result as your original code, but with the efficiency of only calling calculate(i) once per iteration:
it took: [your measured time] seconds to execute with walrus! [6, 14, 30, 54, 86]
内容的提问来源于stack exchange,提问作者Hamzah Zabin

