如果变量不是 None 并且大于一行中的某个值,如何在 python 中检查?

pet*_*huk 2 python python-2.7

如何在一行中做出这个声明?

if x is not None:
    if x > 0:
        pass
Run Code Online (Sandbox Code Playgroud)

如果我只用“和”写,如果没有,它会显示异常

if x is not None and x > 0:
     pass
Run Code Online (Sandbox Code Playgroud)

Aja*_*588 6

您还可以使用 python 三元运算符。在您的示例中,这可能对您有所帮助。您也可以进一步扩展相同的内容。

#if X is None, do nothing
>>> x = ''
>>> x if x and x>0 else None
#if x is not None, print it
>>> x = 1
>>> x if x and x>0 else None
1
Run Code Online (Sandbox Code Playgroud)

处理字符串值

>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>
Run Code Online (Sandbox Code Playgroud)