Skip to main content
 首页 » 编程设计

python之使用自定义比较器按任一元组值对元组字典进行排序

2025年05月04日12sharpest

我正在处理一些元组的 python 字典。每个元组包含 2 个整数。元组中的第一个数字被称为值,第二个数字被称为工作。我有 3 个不同的比较器,我需要将字典按降序排序。此顺序应由调用哪个比较器来确定。也就是说,可以用 3 种不同的方式对字典进行排序。我已经尝试了尽可能多的不同方法来使它起作用。我可以在不使用比较器的情况下做到这一点,只需将它分解成一个列表并通过切片元组进行排序,但如果有人可以阐明使用比较器进行排序的语法,我将不胜感激。我的 cmpWork 似乎正确返回,但其他 2 个没有反转。
如果我能得到按元组值排序的字典,那就太好了。 我有点喜欢

sortedSubjects = sorted(tmpSubjects.iteritems(), key = operator.itemgetter(1), reverse = True)   

但这并不能让我对元组进行切片。
第一次发博文,如有错误请见谅。

def cmpValue(subInfo1, subInfo2):   
    return cmp(subInfo2[0] , subInfo1[0]) 
 
def cmpWork(subInfo1, subInfo2):   
    return cmp(subInfo1[1] , subInfo2[1])   
 
def cmpRatio(subInfo1, subInfo2):   
    return cmp((float(subInfo2[0]) / subInfo2[1]) , (float(subInfo1[0]) / subInfo1[1]))   
 
def greedyAdvisor(subjects, comparator):   
    tmpSubjects = subjects.copy()   
    sortedSubjects = sorted(tmpSubjects.values(), comparator, reverse = True)    
    print sortedSubjects   
 
 
smallCatalog = {'6.00': (16, 8),'1.00': (7, 7),'6.01': (5, 3),'15.01': (9, 6)}   
greedyAdvisor(smallCatalog, cmpRatio)   
greedyAdvisor(smallCatalog, cmpValue)   
greedyAdvisor(smallCatalog, cmpWork)   
 
[(7, 7), (9, 6), (5, 3), (16, 8)]   
[(5, 3), (7, 7), (9, 6), (16, 8)]   
[(16, 8), (7, 7), (9, 6), (5, 3)]   

附上
线路

sortedSubjects = sorted(tmpSubjects.iteritems(), key = operator.itemgetter(1), reverse = True) 

返回

[('6.00', (16, 8)), ('15.01', (9, 6)), ('1.00', (7, 7)), ('6.01', (5, 3))]   

这几乎正是我要找的东西,只是我不能按元组中的第二个值排序,而且我也不能按 cmpRatio 排序。

请您参考如下方法:

but this doesn't let me slice the tuples

从你的例子开始:

sortedSubjects = sorted(tmpSubjects.iteritems(), 
                        key=operator.itemgetter(1), 
                        cmp=comparator,   # What about specifying the comparison? 
                        reverse=True)