2016-08-12 110 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)

相關問題