I want to define comparator like:
def cmp_smth(x, y):
if x == y:
return 0
elif fn(x, y):
return -1
else:
return 1
comparator = functools.cmp_to_key(cmp_smth)
And it works fine with cmp_to_key
converter, ie:
sorted([x, y, z], key=comparator)
But what if I want to sort something more complicated, ie tuples:
sorted([(1, x), (2, y), (3, z)], key=???)
How to use my global comparator in this case?
您可以使用lambda将键函数(以前是比较器)映射到每个元组的第二个元素:
sorted([(1, x), (2, y), (3, z)], key=lambda x: comparator(x[1]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.