有没有更干净的方法来使用二维数组?

Car*_*ate 1 python multidimensional-array python-3.x

我正在尝试创建一个二维数组类,但遇到了问题。我能想到的最好方法是将索引的元组传递给 get/setitem,并将其解压缩到函数中。不幸的是,实现看起来非常混乱:

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])
Run Code Online (Sandbox Code Playgroud)

我试着让它接受更多参数:

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])
Run Code Online (Sandbox Code Playgroud)

但这会导致一个奇怪的类型错误,告诉我我没有传递足够的参数(我猜下标运算符中的任何内容都被视为 1 个参数,即使有逗号)。

(是的,我知道,上面的类实际上并不是一个 2D 数组。我想在开始实际制作 2D 之前先弄清楚运算符。)

有没有一种标准的方法看起来更干净?谢谢

Tha*_*yne 6

有几种方法可以做到这一点。如果你想要像 那样的语法test[1][2],那么你可以__getitem__返回一个列(或行),它可以再次被索引__getitem__(或者甚至只是返回一个列表)。

但是,如果您想要语法test[1,2],那么您就在正确的轨道上,test[1,2]实际上将元组传递(1,2)__getitem__函数,因此在调用它时不需要包含括号。

您可以像这样使__getitem____setitem__实现不那么混乱:

def __getitem__(self, indices):
    i, j = indices
    return (self.data[i], self.data[j])
Run Code Online (Sandbox Code Playgroud)

__getitem__当然,您的实际实施。关键是您已将索引元组拆分为适当命名的变量。