python - 在Python中混合 `str`和 `None`类型时比较一个元组是否更大

标签 python tuples comparison

我有两个元组列表,它们混合了 strNone 类型,需要比较它们,考虑到 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/

相关文章:

python - Pandas 数据帧 : averaging values in one col because another col has duplicates

python - Django ModuleNotFoundError

scala - 分解函数参数中的元组

java - java中如何检查一个列表是否是另一个列表的子集?

将结构体与指针成员进行比较

python - 保存 matplotlib 动画会导致错误

c# - 具有从 Python 2.7 调用的 Iset<> 输入的 .NET C# 方法

python - 如何将版本号字符串存储在 django 数据库中,以便它们可以正确比较/排序

python - 计算嵌套列表中的所有元组元素

javascript - 记住比较器函数的参数顺序的技巧是什么?