Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the specific locations of an integer list in Python?

Tags:

python

numpy

I have an integer list which should be used as indices of another list to retrieve a value. Lets say we have following array

    a = [1,2,3,4,5,6,7,8,9]

We can get the specific elements using following code

    import operator
    operator.itemgetter(1,2,3)(a)

It will return the 2nd, 3rd and 4th item.

Lets say i have another list

    b=[1,2,3]

But if I try to run the following code it gets an error

    operator.itemgetter(b)(a)

I am wondering if someone could help me please. I think its just the problem that I have to convert the b to comma seprated indices butnot very sure.

Thanks a lot

like image 939
Shan Avatar asked Dec 22 '22 09:12

Shan


1 Answers

Use *:

operator.itemgetter(*b)(a)

The * in a function call means, unpack this value, and use its elements as the arguments to the function.

like image 193
Ned Batchelder Avatar answered Dec 24 '22 02:12

Ned Batchelder