繁体   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