2012-04-13 37 views
0

我有這本字典,它存儲了兩對測驗分數和參與者的ID。該結構是{(quiz1,quiz2):ID}訪問字典中的元組

scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084', 
('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'): 
'39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011', 
('66', '89'): '58272'} 

我想使該程序通過進入一對測驗分數來查找的ID。例如,如果用戶輸入測驗1和測驗2的83和93,它將返回81937.自從最近48小時以來,我一直在處理這個問題,但是沒有一個代碼能夠工作...

是否有可能找到兩個測驗最接近的可用分數並打印ID?

回答

4

我已經驗證了您的解決方案可與ipython

In [1]: scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084', 
    ...: ('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'): 
    ...: '39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011', 
    ...: ('66', '89'): '58272'} 

In [2]: scoredict['83','93'] 
Out[2]: '81937' 
+0

噢,我的壞。謝謝你讓我知道! – DarsAE 2012-04-14 02:54:01

0

簡單地做:

>>> scoredict[(score1,score2)] 
1

對於最接近分數,你可以試試這個:

test = (83, 93) 

deviation = float('inf') 
best_match = None 

for score1, score2 in scoredict: 
    error = abs(int(score1) - test[0]) + abs(int(score2) - test[1]) 

    if error < deviation: 
    deviation = error 
    best_match = (score1, score2) 

print scoredict[best_match] 
+0

我試圖使用這種方法,但我得到了這個錯誤: ValueError:無效的文字爲int()與基地10:'-140.0' – DarsAE 2012-04-14 02:54:40

+0

如果您使用浮點使用float()而不是int數字。 – Blender 2012-04-14 04:15:44