在Python 2中,您可以将None与整数和浮点数进行比较,这是通过比较来找到最小的数。但是在Python 3中,它们无法进行比较。您在Python 3中是否有其他替代关键字或解决方案?
TypeError: '>' not supported between instances of 'int' and 'NoneType'
您可以使用条件(三级)运算符,即代替:
if x > y:
用途:
if (0 if x is None else x) > (0 if y is None else y):
在允许无类型的那些字段中,您可以首先检查变量的类型是否为无,如果不满足条件,则继续检查整数:
if x is not None:
if x > y:
# proceed with the operations
由于None
在Python 2中实际上充当负无穷大[*],因此您可以使用(代替x < y
)
False if y is None else True if x is None else x < y
我们首先检查y
,以便当False
和x
均为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