简体   繁体   中英

How to create 2D arrays in Python

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

You want a dict (as associative array/map) which in python is defined with {} . [] is python's list datatype.

state = {
    "PLAYER": {
        "x": 0, 
        "y": 0, 
        "ammo": 0, 
        "state": 0, 
        "last": 0
    }, 
    "ENEMY": {
        "x": 0, 
        "y": 0, 
        "ammo": 0, 
        "state": 0, 
        "last": 0
    }
}

You can have a list of lists, for example:

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

BUT all python lists are indexed by integer. If you want to index by a string, you need a dict .

In this case, you might like a 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

That said, if you are storing identical sets of fields, it might be best to create a class, instantiate objects from it, and then just store the objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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