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) PLAY
Solution 1:
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
Solution 2:
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
}
}
Solution 3:
You can have a list of lists, for example:
In [1]: [[None]*3for n inrange(3)]
Out[1]: [[None, None, None], [None, None, None], [None, None, None]]
In [2]: lol = [[None]*3for n inrange(3)]
In [3]: lol[1][2]
In [4]: lol[1][2] ==NoneOut[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.
Post a Comment for "How To Create 2d Arrays In Python"