我试图在Python中创建一个索引的2D数组,但我一直在以某种方式遇到错误。
以下代码:
#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
我习惯使用PHPs数组,例如:
$array['player']['ammo'] = 5;
Python中有类似的东西吗?我听说人们推荐numpy,但我无法弄明白:(
我是这个Python的新手。
注意:使用Python 2.7
答案 0 :(得分:3)
我认为你应该看看python的data structures tutorial,你在寻找的是一个字典,这是一个键值对列表。
在您的情况下,您可以使用嵌套字典作为键的值,以便您可以调用
## 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中所做的每个元素
答案 1 :(得分: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 :(得分:0)
您可以拥有一个列表列表,例如:
In [1]: [[None]*3 for n in range(3)]
Out[1]: [[None, None, None], [None, None, None], [None, None, None]]
In [2]: lol = [[None]*3 for n in range(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
也就是说,如果要存储相同的字段集,最好创建一个类,从中实例化对象,然后只存储对象。