python - 如何在 Python 中创建二维数组

标签 python arrays vector 2d

我试图在 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/

相关文章:

javascript - v-for 循环项目不会立即在 Vue 中更新

c++ - 关于使用新运算符的 C++ 范围

c++ - 为什么我不能使用 fstream vector ?

c++ - 为什么 C++ 编译器找不到运算符 <<

python - 使用 Python (pysftp) 将文件上传到 SFTP 失败并显示 "No such file"

python pandas read_csv如何加快处理时间戳

javascript - 导出数组 ReactJS - 错误 : array is read-only

c - 重力模拟器、碰撞检测、 vector

python - 在二叉树中查找所有根到叶的路径(在 Python 中)

python - 使用 .read() 从文件对象中提取文本