使用比较器功能进行排序 [英] Using a comparator function to sort
问题描述
因此,我正在使用一些预先存在的比较器,它们比较两个元组中的某些值,如果第一个大于第二个,则返回true,否则返回false.这是其中之一的代码:
So I'm working with a few pre-existing comparators that compare certain values in two tuples and return true if the first is greater than the second, false if otherwise. Here's the code for one of them:
def cmpValue(subInfo1, subInfo2):
"""
Returns True if value in (value, work) tuple subInfo1 is GREATER than
value in (value, work) tuple in subInfo2
"""
# TODO...
if subInfo1[0] > subInfo2[0]:
return True
else:
return False
现在,我有一个字典,其中包含许多上面比较类型的元组条目.我想按相反的顺序对它们进行排序,但是我不太了解如何实现.我在想类似的东西:
Now, I have a dictionary that has numerous tuple entries of the type being compared above. I want to sort them all in reverse order, but I don't really understand how I would accomplish that. I was thinking something like:
sortedDict = sorted(subjects, key=comparator, reverse = True)
但是我不知道将什么传递给比较器,因为每个比较器都带有两个参数(subInfo1,subInfo2). 我无法更改比较器功能.
But I don't know what to pass into the comparator because each comparator takes two arguments (subInfo1, subInfo2). I cannot change the comparator functions.
推荐答案
您将比较器作为key
函数传递.您应该将其作为cmp
传递,并包装在某种将其转换为适当比较器的函数中.
You're passing the comparator as the key
function. You should be passing it as the cmp
, wrapped in some kind of function that turns it into a proper comparator.
def make_comparator(less_than):
def compare(x, y):
if less_than(x, y):
return -1
elif less_than(y, x):
return 1
else:
return 0
return compare
sortedDict = sorted(subjects, cmp=make_comparator(cmpValue), reverse=True)
(尽管实际上,您应该使用关键功能:
(Although actually, you should be using key functions:
sorted(subjects, operator.itemgetter(0), reverse=True)
还要注意,sortedDict
实际上不是dict
,因此名称相当混乱.)
Also note that sortedDict
will not actually be a dict
, so the name is rather confusing.)
这篇关于使用比较器功能进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!