简体   繁体   中英

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, eg

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?

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

Using numpy :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM