I am trying to create a Python list that contains indices of the elements equal to 1 in another integer list (or Numpy array). What I am trying is something like this (for either 1- or 2-dimensional case):
#--- 1D case ---
A = [ 1, 0, 0, 1, 1 ]
idx = []
for i in range( len( A ) ):
if A[ i ] == 1 : idx.append( i )
print( idx ) # [ 0, 3, 4 ]
#--- 2D case ---
B = [ [ 1, 0, 0, 1, 1 ], [ 0, 1, 1 ] ]
idx2 = [ [] for i in range( len( B ) ) ]
for i in range( len( B ) ):
for j in range( len( B[ i ] ) ):
if B[ i ][ j ] == 1 : idx2[ i ].append( j )
print( idx2 ) #[ [0,3,4], [1,2] ]
This may also be written more compactly as
#--- 1D case ---
idx = [ i for i in range( len(A) ) if A[ i ] == 1 ]
#--- 2D case ---
idx2 = []
for i in range( len( B ) ):
tmp = [ k for k in range( len(B[ i ]) ) if B[ i ][ k ] == 1 ]
idx2.append( tmp )
But I am wondering if there is an even more compact way (or builtin function) that can be used for the same purpose. Is there any such convenient function in pure Python, Numpy, or elsewhere...?