给出以下dict
:
class Object:
def __repr__(self): return "Object"
foo = {
1: [(10, Object()), (10, Object())],
2: [(11, Object()), (10, Object())]
}
sorted(foo.items(), key= lambda x : x[1][0], reverse=True)
使用排序的函数,产生预期的结果
[
(2, [(11, Object), (10, Object)]),
(1, [(10, Object), (10, Object)])
]
当dict
中所有值的第一项都相同时,就会出现问题。
foo2 = {
1: [(10, Object()), (10, Object())],
2: [(10, Object()), (10, Object())]
}
由于__lt__()
中未实现Object
,因此sorted()
引发了TypeError
异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Object' and 'Object'
在这种情况下,排序不是必需的,但是无论如何我都需要使用算法。
我该怎么做才能避免此错误?
答案 0 :(得分:1)
只需添加更多索引:
key=x[1][0][0]
演示:
>>> sorted(foo2.items(), key=lambda x: x[1][0][0], reverse=True)
[(1, [(10, Object), (10, Object)]), (2, [(10, Object), (10, Object)])]
按字母顺序比较两个单词,首先是第一个元素,然后当第一个元素相等时再比较第二个元素,依此类推。
但是,如果您不希望将整个元组用于排序,则解决方案是不传递整个元组。仅传入第一个元素,然后按输入顺序打破联系。对于3.6之前的Python版本的词典,这意味着未定义顺序(请参见Why is the order in dictionaries and sets arbitrary?)。
在我的演示中,我使用Python 3.7,并且由于两种情况下第一个元组的第一个元素均为10,因此输出与键的定义顺序相同; 2之前1。