有没有更干净的方法来使用二维数组? [英] Is there a cleaner way to use a 2 dimensional array?
问题描述
我正在尝试创建一个二维数组类,但遇到了问题.我能想到的最好方法是将索引的元组传递给 get/setitem,并将其解压缩到函数中.不幸的是,实现看起来非常混乱:
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])
但这会导致一个奇怪的类型错误,告诉我我没有传递足够的参数(我猜下标运算符中的任何内容都被视为 1 个参数,即使有逗号).
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
推荐答案
有几种方法可以做到这一点.如果你想要像 test[1][2]
这样的语法,那么你可以让 __getitem__
返回一个列(或行),它可以用 __getitem__ 再次索引
(甚至只是返回一个列表).
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).
然而,如果你想要语法test[1,2]
,你就走在正确的轨道上,test[1,2]
实际上传递了元组(1,2)
到 __getitem__
函数,因此您在调用它时不需要包含括号.
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.
您可以像这样使 __getitem__
和 __setitem__
实现不那么混乱:
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])
当然是您对 __getitem__
的实际实现.关键是您已将索引元组拆分为适当命名的变量.
with your actual implementation of __getitem__
of course. The point being that you have split the indices tuple into appropriately named variables.
这篇关于有没有更干净的方法来使用二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!