Im trying to create an indexed 2D array within Python, but I keep running into errors, one way or another.
The following code:
#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
Creates this output:
0 [[0, 0, 0, 0, 0]]
1 [0, 1, [0, 0, 0, 0, 0]]
IndexError: list assignment index out of range
Im used to using PHPs arrays, eg:
$array['player']['ammo'] = 5;
Is there anything similar in Python? I heard people recommending numpy, but i couldn't figure it out :(
Im new to this Python stuff.
Note: Using Python 2.7
解决方案
i think you should have a look at python's data structures tutorial and what you're looking for is called a dictionary here, which is a list of key-value pairs.
in your case, you could use a nested dictionary as a value for a key, so that you could call
## 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}
and access every element like you did in php