I would like use something like that:
class Board():
...
def __getitem__(self, y, x):
return self.board[y][x]
but unfortunatelly, when I call:
board[x][y]
I get:
TypeError: __getitem__() takes exactly 3 arguments (2 given)
In Python, Multidimensional Array can be implemented by fitting in a list function inside another list function, which is basically a nesting operation for the list function. Here, a list can have a number of values of any data type that are segregated by a delimiter like a comma.
Traversing in a 2D array in python can be done by using a for loop. We can iterate through the outer array first and then at each element of the outer array, we have another array which is our inner array containing the elements. So for each inner array, we run a loop to traverse its elements.
When you do board[x][y]
you will cause two calls to __getitem__
because you are doing two separate accesses: [x]
is one and [y]
is another. There's no way to handle this directly in __getitem__
; you'd have to have board[x]
return some kind of sub-object that you could use [y]
on to get the individual item. What you probably want is to have __getitem__
accept a tuple:
def __getitem__(self, tup):
y, x = tup
return self.board[y][x]
Then do:
board[x, y]
(Note that you have the order of x and y switched between __getitem__
and board[x][y]
--- is that intentional?)
You might want to consider using this syntax:
board[(x, y)]
It's less pretty, but it allows you to have multidimensional arrays simply. Any number of dimensions in fact:
board[(1,6,34,2,6)]
By making board a defaultdict you can even have sparse dictionaries:
board[(1,6,34,2,6)]
>>> from collections import defaultdict
>>> board = defaultdict(lambda: 0)
>>> board[(1,6,8)] = 7
>>> board[(1,6,8)]
7
>>> board[(5,6,3)]
0
If you want something more advanced than that you probably want NumPy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With