Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - is there a way to implement __getitem__ for multidimension array?

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)

like image 217
IProblemFactory Avatar asked Jul 04 '13 21:07

IProblemFactory


People also ask

How does Python handle multidimensional arrays?

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.

Which method takes 2 dimensional data in Python?

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.


2 Answers

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?)

like image 68
BrenBarn Avatar answered Sep 19 '22 17:09

BrenBarn


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.

like image 27
Lennart Regebro Avatar answered Sep 19 '22 17:09

Lennart Regebro