用Pythonic方式创建空的向量向量向量映射

1 投票
4 回答
925 浏览
提问于 2025-04-16 06:53

我有以下的C++代码

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'

4 个回答

0

创建一个字典,这个字典里面有一个嵌套的列表,而这个嵌套的列表里又包含了另一个嵌套的列表。

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

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

Python是一种动态语言,也就是说它的类型是隐式的,所以没有“向量的向量的向量的映射”这种说法(在Python里可以理解为“列表的列表的列表的字典”)。字典就是字典,可以包含任何类型的值。而一个空字典就是简单的:{}

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

撰写回答