可能的最佳方法是使用一个字典对于外部容器与用于键映射字符串到内字典,元组(该矢量索引)映射到双:
d = {'abc': {(0,0,0): 1.2, (0,0,1): 1.3}}
这也可能是低效率的(更短的时间效率至少,它实际上更节省空间我会想象)比实际嵌套的名单,但恕我直言吸尘器访问:
>>> d['abc'][0,0,1]
1.3
编辑
添加键作为你去:
d = {} #start with empty dictionary
d['abc'] = {} #insert a new string key into outer dict
d['abc'][0,3,3] = 1.3 #insert new value into inner dict
d['abc'][5,3,3] = 2.4 #insert another value into inner dict
d['def'] = {} #insert another string key into outer dict
d['def'][1,1,1] = 4.4
#...
>>> d
{'abc': {(0, 3, 3): 1.3, (5, 3, 3): 2.4}, 'def': {(1, 1, 1): 4.4}}
或者,如果使用Python> = 2.5,一个更优雅的解决方案是使用defaultdict:它的工作原理就像一个正常的字典,但可以创建不存在的键的值。
import collections
d = collections.defaultdict(dict) #The first parameter is the constructor of values for keys that don't exist
d['abc'][0,3,3] = 1.3
d['abc'][5,3,3] = 2.4
d['def'][1,1,1] = 4.4
#...
>>> d
defaultdict(<type 'dict'>, {'abc': {(0, 3, 3): 1.3, (5, 3, 3): 2.4}, 'def': {(1, 1, 1): 4.4}})
重新编辑:Python通常没有autovivification(不像Perl)。因此,您无法指定不存在的键/索引并使插槽弹簧存在。通过使用'defaultdict',您可以使用有限的形式进行autovification;通过使用'self.details = defaultdict(list)',你可以有一个dict,它自动在空列表中访问一个不存在的键。但是,对于列表中不存在的索引,您无法做到这一点。 – 2010-11-11 04:10:15