可能的最佳方法是使用一個字典對於外部容器與用於鍵映射字符串到內字典,元組(該矢量索引)映射到雙:
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