2016-08-12 109 views
1

我需要一个Python结构,它将整数索引映射到浮点数的向量。我的数据是这样的:unordered_map <int,vector <float>>在Python中相当于

[0] = {1.0, 1.0, 1.0, 1.0} 
[1] = {0.5, 1.0} 

如果我用C写这篇++我会用下面的代码定义/添加/访问如下:

std::unordered_map<int, std::vector<float>> VertexWeights; 
VertexWeights[0].push_back(0.0f); 
vertexWeights[0].push_back(1.0f); 
vertexWeights[13].push_back(0.5f); 
std::cout <<vertexWeights[0][0]; 

什么是这等同结构蟒蛇?

回答

1

dictionary这种格式的 - >{ (int) key : (list) value }

d = {} # Initialize empty dictionary. 
d[0] = [1.0, 1.0, 1.0, 1.0] # Place key 0 in d, and map this array to it. 
print d[0] 
d[1] = [0.5, 1.0] 
print d[1] 
>>> [1.0, 1.0, 1.0, 1.0] 
>>> [0.5, 1.0] 
print d[0][0] # std::cout <<vertexWeights[0][0]; 
>>> 1.0 
+0

在c + +中,如果没有一个键让我们说d [15],那么它会自动创建。但在Pyhton中,我得到了一个关键错误。有没有办法解决这个问题? – Cihan

+0

Yep,C++和python在这方面以相同的方式工作。更新了我的答案。 Python的字典文字本质上是一个无序的映射。 @Cihan – ospahiu

+1

@Cihan尝试['''collections.defaultdict(list)'''](https://docs.python.org/3/library/collections.html#collections.defaultdict)。 – wwii

0

我会去dict与整数作为键和list作为项目,例如,

m = dict() 
m[0] = list() 
m[0].append(1.0) 
m[0].append(0.5) 
m[13] = list() 
m[13].append(13.0) 

,如果它没有太多的数据

+1

应该有'米[13] =列表()''之前米[13] .append(13.0)'。 – Shubham

+0

当然你是正确的 – ChE

2

如何解释并列出这样的:

>>> d = {0: [1.0, 1.0, 1.0, 1.0], 1: [0.5, 1.0]} 
>>> d[0] 
[1.0, 1.0, 1.0, 1.0] 
>>> d[1] 
[0.5, 1.0] 
>>> 

键可以是整数和相关的值可以存储为一个列表。 Python中的字典是散列图,复杂度为分期付款O(1)

相关问题