You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python列表推导式的if条件中正确结合海象运算符与取模运算符?

Fixing Walrus Operator Usage in List Comprehension

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)) evaluates calculate(i) once, assigns that full value to result, 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:

  1. 写法一:

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

    Here, you're assigning the boolean result of calculate(i) %2 == 0 to result. So every time the condition passes, you're adding True to the list instead of the calculated number.

  2. 写法二:

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

    This time, you're assigning the remainder of calculate(i) % 2 to result. When the condition passes, that remainder is 0, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:52:25