【问题标题】:Accessing tuples in dictionary访问字典中的元组
【发布时间】:2012-04-13 23:11:00
【问题描述】:

我有这本字典,它存储成对的两个测验分数和参与者的 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?

【问题讨论】:

    标签: python


    【解决方案1】:

    我已验证您的解决方案已适用于 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'
    

    【讨论】:

    • 哦,我的错。谢谢你告诉我!
    【解决方案2】:

    对于最接近的分数,你可以试试这个:

    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]
    

    【讨论】:

    • 我尝试使用此方法,但出现此错误:ValueError: invalid literal for int() with base 10: '-140.0'
    • 如果您使用浮点数,请使用 float() 而不是 int()
    【解决方案3】:

    简单地做:

    >>> scoredict[(score1,score2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      相关资源
      最近更新 更多