2012-02-29 87 views
3

我試圖在Python中創建一個索引二維數組,但我一直以各種方式遇到錯誤。如何在Python中創建二維數組

下面的代碼:

#Declare Constants (no real constants in Python) 
PLAYER = 0 
ENEMY = 1 
X = 0 
Y = 1 
AMMO = 2 
CURRENT_STATE = 3 
LAST_STATE = 4 

#Initilise as list 
information_state = [[]] 
#Create 2D list structure 
information_state.append([PLAYER,ENEMY]) 
information_state[PLAYER].append ([0,0,0,0,0])#X,Y,AMMO,CURRENT_STATE,LAST_STATE 
information_state[ENEMY].append([0,0,0,0,0])#X,Y,AMMO,CURRENT_STATE,LAST_STATE 


for index, item in enumerate(information_state): 
     print index, item 

information_state[PLAYER][AMMO] = 5 

創建此輸出:

0 [[0, 0, 0, 0, 0]] 
1 [0, 1, [0, 0, 0, 0, 0]] 
IndexError: list assignment index out of range 

林習慣使用PHP的陣列,例如:

$array['player']['ammo'] = 5; 

有什麼在Python相似?我聽人建議numpy的,但我無法弄清楚:(

進出口新的這條巨蟒的東西

注意:使用Python 2.7

回答

3

我想你應該看看Python的data structures tutorial和你looki什麼ng for在這裏被稱爲字典,這是一個鍵值對的列表。

你的情況

,你可以使用嵌套的字典作爲一個鍵的值,這樣你可以調用

## just examples for you ## 

player_dict_info = {'x':0, 'y':0, 'ammo':0} 
enemy_dict_info = {'x':0, 'y':0, 'ammo':0} 
information_state = {'player': player_dict_info, 'enemy': enemy_dict_info} 

和你一樣在PHP做訪問的每一個元素

+0

謝謝,工作出色,我想知道爲什麼隨機谷歌搜索沒有顯示此..... – Mattisdada 2012-02-29 10:40:03

+2

@Mattisdada:嘗試非隨機搜索。 – Marcin 2012-02-29 10:54:25

+0

我想知道爲什麼我的谷歌搜索在我搜索'python 2d arrays'時返回這個。也許標題可以改爲更好地描述實際解決方案的東西。 – joar 2013-03-30 16:51:08

1

你想要一個dict(如關聯數組/圖),它在Python的定義與{}[]是Python的list數據類型。

state = { 
    "PLAYER": { 
     "x": 0, 
     "y": 0, 
     "ammo": 0, 
     "state": 0, 
     "last": 0 
    }, 
    "ENEMY": { 
     "x": 0, 
     "y": 0, 
     "ammo": 0, 
     "state": 0, 
     "last": 0 
    } 
} 
+2

雖然,如果您有兩組相同的字段,則對象可能是正確的。 – Marcin 2012-02-29 10:48:37

+0

是的,絕對如此。 – beerbajay 2012-02-29 10:52:12

0

你可以有一個例如:列表的列表,例如:

In [1]: [[None]*3]*3 
Out[1]: [[None, None, None], [None, None, None], [None, None, None]] 

In [2]: lol = [[None]*3]*3 

In [3]: lol[1][2] 

In [4]: lol[1][2] == None 
Out[4]: True 

但所有的python列表索引的整數。如果你想通過一個字符串索引,你需要一個dict

在這種情況下,你可能會喜歡一個defaultdict

In [5]: from collections import defaultdict 

In [6]: d = defaultdict(defaultdict) 

In [7]: d['foo']['bar'] = 5 

In [8]: d 
Out[8]: defaultdict(<type 'collections.defaultdict'>, {'foo': defaultdict(None, {'bar': 5})}) 

In [9]: d['foo']['bar'] 
Out[9]: 5 

這就是說,如果你存儲領域的套相同,它可能是最好創建一個類,從中實例化對象,然後就存儲對象。

+0

@RikPoggi不,抱怨downvotes是幼稚的。 – Marcin 2012-02-29 10:55:01