【问题标题】:How do you do two dimensional (x,y) indexing in Python?如何在 Python 中进行二维 (x,y) 索引?
【发布时间】:2013-02-15 12:44:39
【问题描述】:

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

代替:

collection[y][x]

做:

collection[x,y]

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

【问题讨论】:

    标签: python multidimensional-array indexing


    【解决方案1】:

    我找到了this recipe at the python mailing list。有了它,您可以使用索引迭代器访问容器的元素。如果您需要使用 container[index_1, index_2] 表示法,可以使用 Mark 帖子中概述的方法轻松调整。

    >>> from operator import getitem
    >>> from functools import reduce
    >>> l = [1,[2,[3,4]]]
    >>> print(reduce(getitem, [1,1,1], l))
     4
    

    这是python邮件列表中建议的另一种方法,我采用container[index_1, index_2]表示法。

    class FlatIndex(object):
      def __init__(self, l):
        self.l = l
      def __getitem__(self, key):
        def nested(l, indexes):
          if len(indexes) == 1:
            return l[indexes[0]]
          else:
            return nested(l[indexes[0]], indexes[1:])
        return nested(self.l, key)
    
    >>> l = [1,[2,[3,4,[5,6]]]] 
    >>> a = FlatIndex(l)
    >>> print(a[1,1,2,1])
     6
    

    【讨论】:

    • 我看不出这与问题有什么关系。
    • 我将问题与使用可迭代索引从容器中访问元素联系起来。不过这个符号有点难看。我不太了解您要达到的目标,但您的帖子很有见地。
    【解决方案2】:

    使用numpy 数组。

    如果你有一个普通的 Python 数组,你可以把它变成一个 numpy 数组并像你描述的那样访问它的元素:

    a = [[1,2,3],[4,5,6],[7,8,9]]
    A = numpy.array(a)
    print A[1,1]
    

    将打印:

    5
    

    另一个例子:

    A = numpy.zeros((3, 3))
    for i in range(3):
        for j in range(3):
            A[i,j] = i*j
    print A
    

    会给你:

    [[ 0.  0.  0.]
     [ 0.  1.  2.]
     [ 0.  2.  4.]]
    

    【讨论】:

      【解决方案3】:

      关键是要了解 Python 如何进行索引 - 当您尝试使用方括号 [] 对其进行索引时,它会调用对象的 __getitem__ 方法。感谢这个答案为我指明了正确的方向:Create a python object that can be accessed with square brackets

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

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

      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
      

      还有一个配套的 __setitem__ 方法,用于分配方括号中的索引。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-05
        • 1970-01-01
        • 2016-08-02
        • 1970-01-01
        相关资源
        最近更新 更多