How to access specific integer list locations in Python?

I have an integer list that should be used as indices of another list to get the value. Let's say we have an array

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

We can get specific elements using the following code

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

He will return the 2nd, 3rd and 4th positions.

Let's say I have another list

  b=[1,2,3] 

But if I try to run the following code, it will get an error message

  operator.itemgetter(b)(a) 

I am wondering if anyone can help me. I think this is just the problem that I need to convert the value of b to a comma, but not necessarily.

thanks a lot

+4
source share
4 answers

Use *:

 operator.itemgetter(*b)(a) 

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

+8
source

Since you tagged your question with the numpy tag, you might also consider creating an array for this to work:

 from numpy import array a = array([1,2,3,4,5,6,7,8,9]) b = [1,2,3] a[b] 
+3
source

The first argument to itemgetter must be a tuple. You can do this with:

 apply(operator.itemgetter, tuple(b))(a) 

There may be a cleaner / more idotic way of doing this, but this works for your example.

0
source

You can also try:

 map(a.__getitem__, b) 

The code returns a list in Python 2 or an iterator in Python 3. If you need to convert it to a tuple, just put it in tuple() .

0
source

All Articles