Python中如何以最低冗余度编写部分重叠的条件判断?
Pythonic Solution for Overlapping Conditional Checks with Minimal Evaluations
To address your requirement of avoiding redundant evaluations of expensive conditions (especially Y), maintaining the required check order, and keeping run() defined only once, here's a concise Pythonic approach using the walrus operator (:=) to cache the result of Y when needed:
y = None trigger = ( (A() and (y := Y()) and a()) or (B() and (y if y is not None else (y := Y())) and b()) or (C() and c()) ) if trigger: run()
How this works:
- Order compliance:
Ais checked beforeY,Ybeforea;Bis checked beforeY,Ybeforeb—matches your required sequence. - Minimal evaluations:
Yis computed at most once: ifAis true, we store its result iny; ifAis false butBis true, we computeYonce (only if it wasn't already evaluated forA).- All conditions (
A,B,C,a,b) are checked only when necessary, thanks to Python's short-circuit evaluation ofor.
- Single
run()call: The trigger condition is evaluated once, andrun()is executed only if any valid branch is true.
Alternative: Helper Function for Enhanced Readability
If you prefer more explicit logic over concise syntax, a helper function makes the flow easier to follow:
def should_run(): y_result = None # Check first branch: A → Y → a if A(): y_result = Y() if y_result and a(): return True # Check second branch: B → Y (cached if possible) → b if B(): if y_result is None: y_result = Y() if y_result and b(): return True # Check third branch: C → c if C() and c(): return True return False if should_run(): run()
This function follows the same logic but breaks it into discrete steps, making it straightforward to modify or debug later.
内容的提问来源于stack exchange,提问作者WeCanDoItGuys
相关产品推荐
相关产品推荐

