如何仅当两个值均不为None时才执行相等性判断?
Solution
To meet your requirement—only running the equality check when both foo and bar are not None (and skipping the check if either or both are None), adjust your condition to first confirm neither value is None:
foo = a bar = a if foo is not None and bar is not None and foo == bar: pass
Explanation
foo is not None and bar is not None: This ensures both variables hold non-None values before proceeding to the equality check. Usingis not Noneis Python's standard practice for verifying against the singletonNoneobject.- The equality check
foo == baronly executes when both values are non-None. If either (or both) isNone, the entire condition evaluates toFalse, so the code inside theifblock won't run.
If you prefer more readable structure, you can split the checks into nested conditions (this achieves the same result):
foo = a bar = a if foo is not None and bar is not None: if foo == bar: pass
内容的提问来源于stack exchange,提问作者dataviews
相关产品推荐
相关产品推荐

