比较前检查值是否不是 none

Check if value is not none before comparison

我正在做一堆操作,基本上是:

if ((x is not None) and (y is not None)) and x > y:
    do_something

我正在对数据 table 的每一行执行此操作,其中某些值为空。是否有更 pythonic 的方式来解决这个问题,而不必每次都检查 None?

不需要括号,None必须大写。否则这基本上是一个很好的方法。您的数据 table 可能会提供一种一次性过滤掉具有 None 值的所有行的方法,这将是一种改进。

没有 'better' 方法可以做到这一点,但是如果你想在一个简短的行中做到这一点并使其更加地道,你可以使用:

do_something() if x is not None and y is not None and (x>y) else do_something_else()

也许:

if not None in (x, y) and x > y:
    do_something()