<分区>
In Python 3 the ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering
如果不存在任何值,这种比较变化会导致难以对元组列表进行排序。
在 Python 2 中:
>>> unordered_list = [('3', '1', None), ('3','1', '4'), ('3', '1', None)]
>>> sorted(unordered_list, reverse=True)
[('3', '1', '4'), ('3', '1', None), ('3', '1', None)]
在 Python 3 中:
>>> unordered_list = [('3', '1', None), ('3','1', '4'), ('3', '1', None)]
>>> sorted(unordered_list, reverse=True)
TypeError: unorderable types: str() < NoneType()
您是否知道如何以优雅的方式使用 Python 2 实现相同的行为?
注意:在上面的例子中我有整数,但这只是一个例子。元组的元素将具有相同的类型,并且它们可以是任何类型。
ex.2 [('test3','test1', 'test4'), ('test3', 'test1', None)]
ex.3 [( 3, 1, 4), (3, 1, None)]
ex.4 [( 3.1, 1.1, 4.1), (3.1, 1.1, None)]