【问题标题】:Iterating through a multidimensional array in Python在 Python 中遍历多维数组
【发布时间】:2010-11-01 13:59:26
【问题描述】:

我在 Python 中创建了一个这样的多维数组:

self.cells = np.empty((r,c),dtype=np.object)

现在我想遍历我的二维数组的所有元素,我不关心顺序。我如何做到这一点?

【问题讨论】:

    标签: python arrays multidimensional-array numpy iteration


    【解决方案1】:

    很明显,您使用的是 numpy.使用 numpy 你可以这样做:

    for cell in self.cells.flat:
        do_somethin(cell)
    

    【讨论】:

    • 我认为现在有一个更有效的方法来做到这一点numpy.nditer()
    【解决方案2】:

    如果您需要更改单个单元格的值,那么 ndenumerate(在 numpy 中)是您的朋友。即使你不这样做,它可能仍然是!

    for index,value in ndenumerate( self.cells ):
        do_something( value )
        self.cells[index] = new_value
    

    【讨论】:

      【解决方案3】:

      只遍历一个维度,然后遍历另一个维度。

      for row in self.cells:
          for cell in row:
              do_something(cell)
      

      当然,只有两个维度,您可以使用 list comprehension 或生成器表达式将其压缩为单个循环,但这不是非常可扩展或可读性:

      for cell in (cell for row in self.cells for cell in row):
          do_something(cell)
      

      如果您需要将其扩展到多个维度并且确实想要一个平面列表,您可以write a flatten function

      【讨论】:

      • 你错了。应该是:for cell in [cell for row in self.cells for cell in row]:do_something(cell)
      • 他的做法不好吗?它只是一个生成器表达式而不是列表理解......我错过了什么吗? O.o
      【解决方案4】:

      您可以使用 enumerate 命令获取每个元素的索引以及元素本身:

      for (i,row) in enumerate(cells):
        for (j,value) in enumerate(row):
          print i,j,value
      

      i,j 包含元素的行和列索引,value 是元素本身。

      【讨论】:

        【解决方案5】:

        这个怎么样:

        import itertools
        for cell in itertools.chain(*self.cells):
            cell.drawCell(surface, posx, posy)
        

        【讨论】:

        • itertools.chain.from_iterable(self.cells)
        【解决方案6】:

        没有 numpy 的情况下,没有人有一个可以在任意多个维度上工作的答案,所以我将在这里放一个我使用过的递归解决方案

        def iterThrough(lists):
          if not hasattr(lists[0], '__iter__'):
            for val in lists:
              yield val
          else:
            for l in lists:
              for val in iterThrough(l):
                yield val
        
        for val in iterThrough(
          [[[111,112,113],[121,122,123],[131,132,133]],
           [[211,212,213],[221,222,223],[231,232,233]],
           [[311,312,313],[321,322,323],[331,332,333]]]):
          print(val)
          # 111
          # 112
          # 113
          # 121
          # ..
        

        这没有很好的错误检查,但对我有用

        【讨论】:

          【解决方案7】:

          可能还值得一提itertools.product()

          cells = [[x*y for y in range(5)] for x in range(10)]
          for x,y in itertools.product(range(10), range(5)):
              print("(%d, %d) %d" % (x,y,cells[x][y]))
          

          它可以创建任意数量的iterables的笛卡尔积:

          cells = [[[x*y*z for z in range(3)] for y in range(5)] for x in range(10)]
          for x,y,z in itertools.product(range(10), range(5), range(3)):
              print("(%d, %d, %d) %d" % (x,y,z,cells[x][y][z]))
          

          【讨论】:

            猜你喜欢
            • 2012-04-16
            • 2021-11-29
            • 2015-09-26
            • 1970-01-01
            • 2013-04-01
            相关资源
            最近更新 更多