我有两个元组列表,它们混合了 str
和 None
类型,需要比较它们,考虑到 None
更大。
a = tuple([None, 4])
b = tuple(['pencil', 12])
a > b
结果:
TypeError: '>' not supported between instances of 'NoneType' and 'str'
如何比较这些项目而不出现该错误?
最佳答案
您还可以子类化tuple
并使用适当实现的__lt__
和__gt__
方法创建您自己的元组类:
class MyTuple(tuple):
def __lt__(self, other):
for s, o in zip(self, other):
if s == o:
continue
if s is None:
return False
if o is None:
return True
return super().__lt__(other)
def __gt__(self, other):
return not self.__lt__(other)
a = MyTuple([None, 4])
b = MyTuple(['pencil', 12])
print(a < b) # False
print(a > b) # True
关于python - 在Python中混合 `str`和 `None`类型时比较一个元组是否更大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53342272/