你如何在Python中进行二维(x,y)索引?

Mar*_*som 2 python indexing multidimensional-array

通常,如果您有二维数据结构,它是两个容器的组合 - 列表列表或字典字典.如果您想制作单个集合但是在二维中工作,该怎么办?

代替:

collection[y][x]
Run Code Online (Sandbox Code Playgroud)

做:

collection[x,y]
Run Code Online (Sandbox Code Playgroud)

我知道这是可能的,因为该PIL Image.load函数返回一个以这种方式工作的对象.

Mar*_*som 5

关键是要了解Python如何进行索引 - __getitem__当您尝试使用方括号对其进行索引时,它会调用对象的方法[].感谢这个答案指向我正确的方向:创建一个可以使用方括号访问的python对象

在方括号中使用一对索引时,将__getitem__使用key参数的元组调用该方法.

这是一个简单的演示类,它在给定二维索引时简单地将整数索引返回到一维列表中.

class xy(object):

    def __init__(self, width):
        self._width = width

    def __getitem__(self, key):
        return key[1] * self._width + key[0]

>>> test = xy(100)
>>> test[1, 2]
201
>>> test[22, 33]
3322
Run Code Online (Sandbox Code Playgroud)

__setitem__在方括号中分配索引时,还会使用伴随方法.