5
subjects = {
    0:9,'fail': 0,
   9:14, 'pass': 25,
   15:17, 'merit': 40,
    18:20,'Distinction': 50
}

我希望上面的字典包含 3 个维度。用户输入将在初始数字之间。根据用户输入的数字,应显示以下消息。例如。4 是不合格 0 分,10 是合格 25 分,以此类推。

inputs = ['irish','english','french','italian','dutch','german']
for i in range(1, 7):
    inputs.append(raw_input('Enter mark for {}: '.format(i)))

我希望循环询问爱尔兰语等的输入标记

print sum(subjects[name][value] for name in inputs)

这可以做到吗?

4

3 回答 3

4

字典基于键的散列存储其值。

这意味着字典查找仅返回其键与查找中使用的键完全匹配的条目。

您不能将键设为“3 到 5 范围内的任何数字”并期望查找“4”。

但是,您可以做的是复制字典条目:

subject_ranges = [(0, 8, 'fail', 0),
                  (9, 14, 'pass', 25),
                  (15, 17, 'merit', 40),
                  (18, 20, 'Distinction', 50)]
subjects = {}
for low, high, descr, points in subject_ranges:
   for score in range(low, high+1):
      subjects[score] = {'description': descr, 'value': points}

并像这样收集输入:

input_names = ['irish','english','french','italian','dutch','german']
scores = []
for i in range(len(input_names)):
    scores.append(int(raw_input('Enter mark for %s: ' % input_names[i])))

现在,此代码将按照您的意愿打印总分:

print sum(subjects[score]['value'] for score in scores)

不是“3 维字典”,也不是类似的东西。它是一个字典,其键是整数,其值是双元素字典(如果您愿意,可以使用 NamedTuple)。但是从您的问题来看,您实际上并不需要比这更复杂的东西。

于 2013-01-08T21:25:22.013 回答
2

您还可以将值范围放入元组中,然后这些元组用作字典的键。(请注意,作为键的列表不起作用,因为它们不可散列。)

In [36]: subjects = {
   ....:     tuple(range(10)): {
   ....:         'descr': 'fail',
   ....:         'points': 0
   ....:     },
   ....:     tuple(range(10, 15)): {
   ....:         'descr': 'pass',
   ....:         'points': 25,
   ....:     },
   ....:     tuple(range(15, 18)): {
   ....:         'descr': 'merit',
   ....:         'points': 40
   ....:     },
   ....:     tuple(range(18, 21)): {
   ....:         'descr': 'Distinction',
   ....:         'points': 50
   ....:     }
   ....: }

然后,您可以像这样查询字典:

In [43]: score = 0

In [44]: vals = [5, 15, 20, 2, 12]

In [45]: for val in vals:
   ....:     for key in subjects:
   ....:         if val in key:
   ....:             score += subjects[key]['points']
   ....:             print subjects[key]['descr']
   ....:             break 
fail
merit
Distinction
fail
pass

In [46]: score
Out[46]: 115
于 2013-01-08T21:53:53.700 回答
1

您可以使用查找范围的自定义范围字典。

#! /usr/bin/python3.2

class RangeDict (dict):
    class AmbiguityException (Exception): pass

    def __getitem__ (self, key):
        hits = [ (a, b) for a, b in self.keys () if a <= key < b]
        if not hits: {} [key]
        if len (hits) > 1: raise RangeDict.AmbiguityException ()
        #for python3
        return super ().__getitem__ (hits [0] )
        #for python2.7:
        #return super (RangeDict, self).__getitem__ (hits [0] )

subjects = { (0, 9): 'fail',
    (9, 15): 'pass',
    (15, 18): 'merit',
    (18, 21): 'Distinction'}

rd = RangeDict (subjects)
for x in range (21): print (x, rd [x] )

编辑:我没有看到python-2.7标签。用户super (cls, inst)而不是super ().

于 2013-01-08T22:20:48.103 回答