2010-11-11 76 views
1

的矢量的矢量的空地圖,我有以下的C++代碼Python化的方式來創建矢量

std::map<std::string, std::vector<std::vector<std::vector<double> > > > details 
details["string"][index][index].push_back(123.5); 

可我知道什麼是Python的申報矢量的矢量的矢量的空白地圖? :P

我努力

self.details = {} 
self.details["string"][index][index].add(value) 

我越來越

KeyError: 'string' 
+0

重新編輯:Python通常沒有autovivification(不像Perl)。因此,您無法指定不存在的鍵/索引並使插槽彈簧存在。通過使用'defaultdict',您可以使用有限的形式進行autovification;通過使用'self.details = defaultdict(list)',你可以有一個dict,它自動在空列表中訪問一個不存在的鍵。但是,對於列表中不存在的索引,您無法做到這一點。 – 2010-11-11 04:10:15

回答

3

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

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}}) 
+0

如何可能有空d,插入工作將在以後完成? – 2010-11-11 03:42:22

+0

@Yan Cheng更新了答案,查看了編輯過的部分。 – user470379 2010-11-11 03:52:59

+0

我不明白你爲什麼需要在字典中放置字典。相反,只需使用d ['abc',0,3],其中d是集合。defaultdict(列表) – 2010-11-11 04:38:04

0

創建一個包含inturn包含嵌套列表

dict1={'a':[[2,4,5],[3,2,1]]} 

dict1['a'][0][1] 
4 
+0

如何可能有空d,插入工作將在以後完成? – 2010-11-11 03:48:14

3

Python是一種嵌套列表字典動態(潛在型)語言,所以不存在「矢量矢量矢量圖」(或「列表字典列表中的列表「在Python中說)。字典只是字符串,可以包含任何類型的值。和一個空的字典很簡單:{}

0

使用collections.defaultdict,你可以嘗試下面的lambda技巧。請注意,您會遇到酸洗這些對象的問題。

from collections import defaultdict 

# Regular dict with default float value, 1D 
dict1D = defaultdict(float) 
val1 = dict1D["1"] # string key type; val1 == 0.0 by default 

# 2D 
dict2D = defaultdict(lambda: defaultdict(float)) 
val2 = dict2D["1"][2] # string and integer key types; val2 == 0.0 by default 

# 3D 
dict3D = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) 
val3 = dict3D[1][2][3] # val3 == 0.0 by default 

# N-D, arbitrary nested defaultdicts 
dict4D = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(str)))) 
val4 = dict4D["abc"][10][9][90] # val4 == '' by default 

你基本上可以嵌套許多這些defaultdict集合類型。另外請注意,它們的行爲與普通的python字典相似,可以使用常用的鍵類型(非可變和可哈希)。祝你好運!