我试图在 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
我习惯使用 PHPs 数组,例如:
$array['player']['ammo'] = 5;
Python 中有类似的东西吗?我听说有人推荐 numpy,但我想不通:(
我是 Python 新手。
注意:使用 Python 2.7
最佳答案
我认为你应该看看 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 中一样访问每个元素
关于python - 如何在 Python 中创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9497322/