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

标签 python python-2.7

如何将这句话写成一行?

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/

相关文章:

python - 获取字符串的每个组合

python - python中的部分字符串匹配

python - 在我的 Raspberry PI 上使用 Python 和 OpenCV 没有保存视频文件

python - 单个 DataFrame 中多行的交集

python - 在 python 中调用 int 的 __init__ 看似微不足道的问题

python - 如何在 Qt Designer 中推广的 QVideoWidget 中播放视频?

python - 在哪里可以找到 Keras 配置文件?

python - 参数化 django 的迁移以跳过(--fake 以编程方式)

python - 使用类装饰器,如何在不重新定义类的情况下重写方法?

Python 2.7-MySQL : Query value won't change while running on infinite loop