簡體   English   中英

在字典中訪問元組

[英]Accessing tuples in dictionary

我有這本字典,用於存儲兩個測驗分數對和參與者的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?

我驗證了您的解決方案已經可以與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'

對於最接近的分數,您可以嘗試以下方法:

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]

只需做:

>>> scoredict[(score1,score2)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM