在 Perl 中,我可以使用索引列表轻松选择多个数组元素,例如:
在Python中,最常见的做法是什么?
my @array = 1..11;
my @indexes = (0,3,10);
print "@array[ @indexes ]"; # 1 4 11
在Python中,最常见的做法是什么?
使用 operator.itemgetter
:
from operator import itemgetter
array = range(1, 12)
indices = itemgetter(0, 3, 10)
print indices(array)
# (1, 4, 11)
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]
numpy
:>>> import numpy as np
>>> indexes = (0,3,10)
>>> x = np.arange(1,12)
>>> x [np.array(indexes)]
array([ 1, 4, 11])