有没有更简洁的方法使用二维数组?

2 投票
1 回答
1898 浏览
提问于 2025-04-18 01:36

我正在尝试制作一个二维数组的类,但遇到了一些问题。我想到的最好办法是把索引作为一个元组传递给获取和设置项的函数,然后在函数内部拆解这个元组。不过,这样实现起来看起来真的很乱:

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

我尝试让它接受更多的参数:

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

但这导致了一个奇怪的类型错误,告诉我传递的参数不够(我想在下标操作符里面的任何东西都被认为是一个参数,即使里面有逗号)。

(是的,我知道,上面的类实际上并不是一个二维数组。我想先搞定操作符的部分,然后再继续制作真正的二维数组。)

有没有什么标准的方法可以让这个看起来更整洁一些?谢谢

1 个回答

7

有几种方法可以实现这个功能。如果你想要像 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])

当然,这里要用你实际的 __getitem__ 实现。关键是你把索引元组拆分成了适当命名的变量。

撰写回答