代码之家  ›  专栏  ›  技术社区  ›  user8188120

以列表形式获取N维数组的所有索引[重复]

  •  2
  • user8188120  · 技术社区  · 6 年前

    在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] ]
    
    5 回复  |  直到 6 年前
        1
  •  3
  •   user3483203    6 年前

    使用 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
  •  1
  •   Sheldore    6 年前

    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
  •  1
  •   sacuL    6 年前

    我建议做一系列的 1 形状和你的一样 test np.ones_like ,然后使用 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
  •  1
  •   slider    6 年前

    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
  •  0
  •   bla    6 年前

    你可以试试 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]]