“ None”不能与数字进行比较。还有其他选择吗?

问题描述 投票:0回答:3

在Python 2中,您可以将None与整数和浮点数进行比较,这是通过比较来找到最小的数。但是在Python 3中,它们无法进行比较。您在Python 3中是否有其他替代关键字或解决方案?

TypeError: '>' not supported between instances of 'int' and 'NoneType'
python python-3.x numbers int nonetype
3个回答
1
投票

您可以使用条件(三级)运算符,即代替:

if x > y:

用途:

if (0 if x is None else x) > (0 if y is None else y):

0
投票

在允许无类型的那些字段中,您可以首先检查变量的类型是否为无,如果不满足条件,则继续检查整数:

if x is not None:
    if x > y:
        # proceed with the operations  

0
投票

由于None在Python 2中实际上充当负无穷大[*],因此您可以使用(代替x < y

False if y is None else True if x is None else x < y

我们首先检查y,以便当Falsex均为y时结果为None

>>> def f(x, y):
...   return False if y is None else True if x is None else x < y
...
>>> f(None, None)
False
>>> f(None, -10000)
True
>>> f(-10000, None)
False

但是,如果要定义一个函数,则为了清楚起见,应使用if语句编写它:

def f(x, y):
    if y is None:
        return False
    if x is None:
        return True
    return x < y
© www.soinside.com 2019 - 2024. All rights reserved.