python - Is there a cleaner way to use a 2 dimensional array? -
i'm trying make 2d array class, , ran problem. best way figure out pass get/setitem tuple of indices, , have unpacked in function. unfortunately though, implementation looks messy:
class ddarray: data = [9,8,7,6,5,4,3,2,1,0] def __getitem__ (self, index): return (self.data [index [0]], self.data [index [1]]) def __setitem__ (self, index, value): self.data [index [0]] = value self.data [index [1]] = value test = ddarray () print (test [(1,2)]) test [(1, 2)] = 120 print (test [1, 2])
i tried having accept more parameters:
class ddarray: data = [9,8,7,6,5,4,3,2,1,0] def __getitem__ (self, index1, index2): return (self.data [index1], self.data [index2]) def __setitem__ (self, index1, index2, value): self.data [index1] = value self.data [index2] = value test = ddarray () print (test [1, 2]) test [1, 2] = 120 print (test [1, 2])
but results in weird type error telling me i'm not passing enough arguments (i guess inside of subscript operator considered 1 argument, if there's comma).
(yes, know, above class isn't 2d array. wanted have operators figured out before moved on making 2d.)
is there standard way of doing looks little cleaner? thanks
there couple ways can this. if want syntax test[1][2]
, can have __getitem__
returns column (or row), can indexed again __getitem__
(or return list).
however, if want syntax test[1,2]
, on right track, test[1,2]
passes tuple (1,2)
__getitem__
function, don't need include parantheses when calling it.
you can make __getitem__
, __setitem__
implementations little less messy so:
def __getitem__(self, indices): i, j = indices return (self.data[i], self.data[j])
with actual implementation of __getitem__
of course. point being have split indices tuple appropriately named variables.
Comments
Post a Comment