如何在一行中做出这个声明?
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)
您还可以使用 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)
| 归档时间: |
|
| 查看次数: |
9170 次 |
| 最近记录: |