如何在Python中创建2D数组 [英] How to create 2D arrays in Python
问题描述
我正在尝试在Python中创建索引的2D数组,但是我一直以一种或另一种方式遇到错误.
Im trying to create an indexed 2D array within Python, but I keep running into errors, one way or another.
以下代码:
#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数组,例如:
Im used to using PHPs arrays, eg:
$array['player']['ammo'] = 5;
Python中有类似的东西吗?我听说有人推荐numpy,但我不知道它是不是:(
Is there anything similar in Python? I heard people recommending numpy, but i couldn't figure it out :(
这是Python的新知识.
Im new to this Python stuff.
注意:使用Python 2.7
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}
并像在php中一样访问每个元素
and access every element like you did in php
这篇关于如何在Python中创建2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!