planetp
planetp

Reputation: 16065

How can I get the list slice using a list of indexes in Python?

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?

Upvotes: 3

Views: 357

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Using numpy:

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

Upvotes: 1

falsetru
falsetru

Reputation: 369074

>>> 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]

Upvotes: 4

Jon Clements
Jon Clements

Reputation: 142156

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

Upvotes: 7

Related Questions