【问题标题】:Get all indices of an N-dimensional array as a list [duplicate]获取N维数组的所有索引作为列表[重复]
【发布时间】:2019-02-24 23:17:53
【问题描述】:

有没有办法在 Python 中快速有效地获取 N 维数组中所有索引的列表或数组?

例如,图像我们有如下数组:

import numpy as np

test = np.zeros((4,4))

array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

我想获取所有元素索引如下:

indices = [ [0,0],[0,1],[0,2] ... [3,2],[3,3] ]

【问题讨论】:

  • 你总是可以使用嵌套的 for 循环
  • 我希望有更快的速度..这不是粗鲁我只是想优化一些代码并获得像上面这样的列表可能是一个好方法:)跨度>
  • itertools 中的某些内容应该能够生成所有组合。
  • 字面意思是numpy.indices
  • 谢谢 numpy.indices 似乎是最简单的!

标签: python arrays numpy element indices


【解决方案1】:

使用np.indices 并稍作修改:

np.indices(test.shape).reshape(2, -1).T

array([[0, 0],  
       [0, 1],  
       [0, 2],  
       [0, 3],  
       [1, 0],  
       [1, 1],  
       [1, 2],  
       [1, 3],  
       [2, 0],  
       [2, 1],  
       [2, 2],  
       [2, 3],  
       [3, 0],  
       [3, 1],  
       [3, 2],  
       [3, 3]])

【讨论】:

    【解决方案2】:

    如果你对使用列表理解没问题

    test = np.zeros((4,4))
    indices = [[i, j] for i in range(test.shape[0]) for j in range(test.shape[1])]
    print (indices)
    
    [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]
    

    【讨论】:

      【解决方案3】:

      我建议使用np.ones_like 创建一个与test 数组形状相同的1 数组,然后使用np.where

      >>> np.stack(np.where(np.ones_like(test))).T
      # Or np.dstack(np.where(np.ones_like(test)))
      array([[0, 0],
             [0, 1],
             [0, 2],
             [0, 3],
             [1, 0],
             [1, 1],
             [1, 2],
             [1, 3],
             [2, 0],
             [2, 1],
             [2, 2],
             [2, 3],
             [3, 0],
             [3, 1],
             [3, 2],
             [3, 3]])
      

      【讨论】:

        【解决方案4】:

        只是枚举应该做的:

        test = [[0., 0., 0., 0.],
               [0., 0., 0., 0.],
               [0., 0., 0., 0.],
               [0., 0., 0., 0.],
               [0., 0., 0., 0.]]
        
        indices = [[i, j] for i, row in enumerate(test) for j, col in enumerate(row)]
        print(indices)
        
        >>> [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3], [4, 0], [4, 1], [4, 2], [4, 3]]
        

        【讨论】:

        • 您可能还想将元组转换为列表
        【解决方案5】:

        你可以试试itertools.product:

        >>> from itertools import product
        >>> 
        >>> [list(i) for i in product(range(4), range(4))]
        [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]
        

        【讨论】:

          猜你喜欢
          • 2016-06-22
          • 2015-03-26
          • 1970-01-01
          • 1970-01-01
          • 2015-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多