排序比较运算符约在Python
3种严格,如描述在这里:
当操作数没有有意义的自然顺序时,顺序比较运算符(<,<=,> =,>)会引发TypeError异常。
Python 2
None在任何字符串(甚至是空字符串)之前进行排序:
>>> None < NoneFalse>>> None < "abc"True>>> None < ""True
在Python 3中,任何对
NoneType实例进行排序的尝试都会导致异常:
>>> None < "abc"Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: unorderable types: NoneType() < str()
我能想到的最快的解决方法是将
None实例显式映射为可排序的对象,例如
"":
my_list_sortable = [(x or "") for x in my_list]
如果您想对数据进行排序同时保持其完整性,则只需提供
sort一个自定义
key方法即可:
def nonesorter(a): if not a: return "" return amy_list.sort(key=nonesorter)



