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

前端 未结 1 1110
时光说笑
时光说笑 2021-01-16 16:33

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 i

相关标签:
1条回答
  • 2021-01-16 17:08

    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.

    0 讨论(0)
提交回复
热议问题