Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - Is there a cleaner way to use a 2 dimensional array?

I'm trying to make a 2D array class, and ran into a problem. The best way I could figure out to do it was to pass get/setitem a tuple of the indices, and have it unpacked in the function. Unfortunately though, the implementation looks really 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 just having it 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 that results in a weird type error telling me that I'm not passing enough arguments (I guess anything inside of the subscript operator is considered 1 argument, even if there's a comma).

(Yes, I know, the above class isn't actually a 2D array. I wanted to have the operators figured out before I moved on to actually making it 2D.)

Is there a standard way of doing it that looks a little cleaner? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple ways you can do this. If you want syntax like test[1][2], then you can have __getitem__ returns a column (or row), which can be indexed again with __getitem__ (or even just return a list).

However, if you want the syntax test[1,2], you are on the right track, test[1,2] actually passes the tuple (1,2) to the __getitem__ function, so you don't need to include the parantheses when calling it.

You can make the __getitem__ and __setitem__ implementations a little less messy like so:

def __getitem__(self, indices):
    i, j = indices
    return (self.data[i], self.data[j])

with your actual implementation of __getitem__ of course. The point being that you have split the indices tuple into appropriately named variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...