lambda x: None if x[1] is None else x[1][0]
这实际上把None放在第一位,因为None似乎比任何东西都少。嗯,很有趣。在
在Python3中,默认情况下不能比较不兼容类型的对象。因此,为了将来的验证,您应该替换一个可以与x[1][0]类型相比较的值。当然,这种方法也适用于python2.x。例如,如果是数字,可以使用:
^{pr2}$
这将使None值全部排序到最后。在
为每个None值计算float("+inf")不是最佳性能;如果这是一个瓶颈,只需定义一次并在lambda中使用它:posinf = float("+inf")
lambda x: posinf if x[1] is None else x[1][0]
如果float("+inf")可能是您的数据的有效值,那么您可能需要一个特殊的类,它总是比任何其他类都大:class Maximus(object):
"Object that is greater than any other object (but equal to itself)."
__le__ = __eq__ = lambda self, other: isinstance(other, type(self))
__ne__ = __gt__ = lambda self, other: not isinstance(other, type(self))
__lt__ = lambda self, other: False
__ge__ = lambda self, other: True
__str__ = lambda self: "I am the greatest!"
__repr__ = lambda self: "Maximus()"
maximus = Maximus()
lambda x: maximus if x[1] is None else x[1][0]
(我相信只有__lt__和__eq__就可以进行排序,但是Maximus拥有完整的比较方法。)