Skip to content
Advertisement

New list based on indices from another list in Python

I have an array X and a list A1. I want to create a new list B1 such that it consists of values from X corresponding to indices in A1. For example, the code should pick values from X[0] for indices in A1[0] and so on…I present the current and expected outputs.

JavaScript

The current output is

JavaScript

The expected output is

JavaScript

Advertisement

Answer

For the ith element of A1, you want to pick elements from the ith row of X, so iterate over A1 and X simultaneously using zip. In the loop, ai is a list containing a single list. This inner list contains the indices you want.

JavaScript

Which gives the desired result:

JavaScript

Note that I converted xi[indices] to a list, but if the result you want is a numpy array then you don’t need to do that, and instead just:

JavaScript

which gives a 2x3 result array:

JavaScript
Advertisement