简体   繁体   English

在字典中访问元组

[英]Accessing tuples in dictionary

I have this dictionary that stores pairs of two quiz scores and participants' ID. 我有这本字典,用于存储两个测验分数对和参与者的ID。 The structure is {(quiz1, quiz2): 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'}

I want to make this program to look up for an ID by entering a pair of quiz scores. 我想通过输入一对测验分数来使该程序查找ID。 Like, for example, if the user input 83 and 93 for quiz 1 and quiz 2, it will return 81937. I've been working on this since the last 48 hours, but none of my codes worked... 例如,如果用户为测验1和测验2输入83和93,它将返回81937。自最近48个小时以来,我一直在从事此工作,但是我的代码都无法正常工作...

And is it possible to find the closest available scores for both quizzes and print the ID? 是否可以找到两个测验的最接近可用分数并打印ID?

I verified your solution already works with ipython : 我验证了您的解决方案已经可以与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'

For the closest scores, you can try this: 对于最接近的分数,您可以尝试以下方法:

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