2013-04-10 50 views
1

我正在研究一些元組的python字典。每個元組包含2個整數。元組中的第一個數字被認爲是value,第二個數字被認爲是work。我有3個不同的比較器,我需要按照降序對字典進行排序。這個順序應該由調用哪個比較器決定。即字典可以按3種不同的方式分類。我嘗試了儘可能多的不同方式,因爲我可以找到這個工作。我可以在不使用比較器的情況下做到這一點,只需將其分解成列表並通過切分元組來排序即可,但如果任何人都可以通過比較器對語法進行排序,那麼將不勝感激。我似乎正在爲cmpWork正確地返回,但其他兩個不會顛倒過來。
如果我能得到按元組值排序的字典,它也會很好。 我有一種與使用自定義比較器對元組的字典進行排序

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)] 

PS

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進行排序。

+0

提示:'sorted'返回一個新列表;無需創建'tmpSubjects'。你可以直接返回'sorted'的結果 – 2013-04-10 13:53:31

回答

1

但是,這並不讓我切片的元組

與您的示例開始:

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

謝謝大家。我不知道我必須導入集合才能使用odereddict,所以非常感謝,並且我將cmp關鍵字從我的排序語句中刪除。當我閱讀Ricardos的答案時才發現它。當我添加它在它正常工作。感謝火山和裏卡多。會讓你知道我如何繼續。 – Loubot 2013-04-10 14:05:58

0

如果需要排序的字典 - 使用collections.OrderedDict 例如,通過排序元組的第一個元素

OrderedDict(sorted(smallCatalog.items(), key=lambda e:e[1][0])) 
Out[109]: OrderedDict([('6.01', (5, 3)), ('1.00', (7, 7)), ('15.01', (9, 6)), ('6.00', (16, 8))]) 
+0

再次感謝你們。得到它的工作。 – Loubot 2013-04-10 15:33:04

相關問題