3

In Perl I can easily select multiple array elements using a list of indexes, e.g.

my @array = 1..11;
my @indexes = (0,3,10);
print "@array[ @indexes ]"; # 1 4 11

What's the canonical way to do this in Python?

3 Answers 3

7

use operator.itemgetter:

from operator import itemgetter
array = range(1, 12)
indices = itemgetter(0, 3, 10)
print indices(array)
# (1, 4, 11)

Then present that tuple however you want..., eg:

print ' '.join(map(str, indices(array)))
# 1 4 11
Sign up to request clarification or add additional context in comments.

2 Comments

wow!! Thanks. From where you get to know all these techniques:)
@rajpy It's worth taking the time (although not all in one sitting) to read through the library reference to see what is there.
4
>>> array = range(1, 12)
>>> indexes = [0, 3, 10]
>>> [array[i] for i in indexes]
[1, 4, 11]
>>>
>>> list(map(array.__getitem__, indexes))
[1, 4, 11]

Comments

1

Using numpy:

>>> import numpy as np
>>> indexes = (0,3,10)
>>> x = np.arange(1,12)
>>> x [np.array(indexes)]
array([ 1,  4, 11])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.