Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting items on a matrix based on indexes given by an array

Consider this matrix:

[0.9, 0.45, 0.4, 0.35],
[0.4, 0.8, 0.3, 0.25],
[0.5, 0.45, 0.9, 0.35],
[0.2, 0.18, 0.8, 0.1],
[0.6, 0.45, 0.4, 0.9]

and this list:

[0,1,2,3,3]

I want to create a list that looks like the following:

[0.9, 0.8, 0.9, 0.1, 0.9]

To clarify, for each row, I want the element of the matrix whose column index is contained in the first array. How can I accomplish this?

like image 725
Lorenzo Cutrupi Avatar asked Oct 23 '25 03:10

Lorenzo Cutrupi


1 Answers

Zip the two lists together as below

a=[[0.9, 0.45, 0.4, 0.35],[0.4, 0.8, 0.3, 0.25],[0.5, 0.45, 0.9, 0.35],[0.2, 0.18, 0.8, 0.1],[0.6, 0.45, 0.4, 0.9]]
b=[0,1,2,3,3]
[i[j] for i,j in zip(a,b)]

Result

[0.9, 0.8, 0.9, 0.1, 0.9]

This basically pairs up each sublist in the matrix with the element of your second list in order with zip(a,b)

Then for each pair you choose the bth element of a

like image 152
EoinS Avatar answered Oct 25 '25 02:10

EoinS