如何在Python中创建二维数组

3

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

我习惯使用PHP的数组,例如:

$array['player']['ammo'] = 5;

在Python中有类似的东西吗?我听说人们推荐使用numpy,但是我没有理解 :(

我刚接触Python。

注:使用的是Python 2.7版本。

3个回答

3
我认为你应该看一下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中一样访问每个元素


谢谢,运行得非常好,我想知道为什么随机的谷歌搜索没有显示这个..... - Mattisdada
2
@Mattisdada:尝试非随机搜索。 - Marcin
我想知道为什么当我搜索“python 2d数组”时,谷歌返回这个结果。也许标题可以改成更好地描述实际解决方案的内容。 - joar

1
你想要一个 Python 中定义为 {}dict(关联数组/映射表)。[] 是 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
    }
}

2
虽然,如果您有两个相同的字段集,则对象可能是正确的选择。 - Marcin

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

话虽如此,如果您正在存储相同的字段集,最好创建一个类,从中实例化对象,然后只需存储对象。


解决方案有误,因为顶部列表中的所有字段都包含对另一个列表的引用,所以实际上这是一维问题。 - Matthias Michael Engh
@MatthiasMichaelEngh 这在什么意义上是错误的? - Marcin
他想知道如何制作一个二维数组。二维意味着由两个独立变量映射的值,但这里并不是这种情况。 - Matthias Michael Engh
@MatthiasMichaelEngh 不,它不是。 - Marcin
尝试运行以下代码:a = [["我是正确的"] * 3] * 3; a[0][1] = "别浪费我的时间"; print a[0][1] == a[1][1] - Matthias Michael Engh
1
@MatthiasMichaelEngh 我现在明白你的意思了。 - Marcin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接