繁体   English   中英

如何在Python中创建2D数组

[英]How to create 2D arrays in Python

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

我想你应该看一下python的数据结构教程 ,你要找的是这里的一个字典,这是一个键值对列表。

在您的情况下,您可以使用嵌套字典作为键的值,以便您可以调用

## 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中所做的每个元素

你想要一个dict (作为关联数组/ map),它在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
    }
}

您可以拥有一个列表列表,例如:

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

也就是说,如果要存储相同的字段集,最好创建一个类,从中实例化对象,然后只存储对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM