Mechanician
Mechanician

Reputation: 545

Find all the row indices of a set of elements in a 2D Array

I have a particular list of numbers(item_list) for which i need all the row indices associated inside a 2D array (C). Please find the code below :

# Sample code
item_list = [1, 2, 3]

C= [[0 for x in range(5)] for x in range(5)]

C[0][:]=[1,5,3,25,30]
C[1][:]=[7,9,15,2,45]
C[2][:]=[2,9,15,78,98]
C[3][:]=[3,90,15,1,98]
C[4][:]=[12,19,25,3,8]

rind=[]

for item in item_list:
    v=[i for i in range(len(C)) for j in range (len(C[i])) if C[i][j]==item ]
    r_ind.append(v)

My 2D array size is ~ 7M *4, could anyone help me make this faster?

Upvotes: 0

Views: 51

Answers (1)

Alex Hall
Alex Hall

Reputation: 36033

For starters:

rind = [[i for i in range(len(C)) if item in C[i]]
        for item in item_list]

The crucial change here is the use of in which should be faster than your manual check.

This also means you won't get the same i multiple times in sublists in the output if a number appears multiple times in a sublist in the input, which I assume is what you really want.

Upvotes: 1

Related Questions