0

Can the following be done without loops?

B = np.array([[0, 1, 2, 3],[1, 0, 3, 5],[2, 3, 0, 6],[3, 5, 6, 0]])
mylist = [0, 1, 0, 2, 3, 0] #note the repeats

BigB = np.zeros((len(mylist),len(mylist)),np.int64)

for i,row in enumerate(mylist):
    for j,col in enumerate(mylist):
        BigB[i,j] = B[row,col]

Output

B
Out[100]: 
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

BigB
Out[101]: 
array([[0, 1, 0, 2, 3, 0],
       [1, 0, 1, 3, 5, 1],
       [0, 1, 0, 2, 3, 0],
       [2, 3, 2, 0, 6, 2],
       [3, 5, 3, 6, 0, 3],
       [0, 1, 0, 2, 3, 0]])

If there were no repeats, I could use direct indexing as in this answer

A. Roy
  • 366
  • 3
  • 12

0 Answers0