2010-11-11 102 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字典相似,可以使用常用的键类型(非可变和可哈希)。祝你好运!