如何将这句话写成一行?
if x is not None:
if x > 0:
pass
如果我只写 'and',如果 None 则显示异常
if x is not None and x > 0:
pass
最佳答案
你也可以使用 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
处理字符串值
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>
关于python - 如果变量不是 None 并且大于一行中的某个值,如何检查 python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53294735/