如何在Python中使用索引列表获取列表切片?

3
在 Perl 中,我可以使用索引列表轻松选择多个数组元素,例如:
my @array = 1..11;
my @indexes = (0,3,10);
print "@array[ @indexes ]"; # 1 4 11

在Python中,最常见的做法是什么?
3个回答

7

使用 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

哇!!谢谢。你是从哪里学到这些技巧的呀 :) - rajpy
1
@rajpy 值得花时间(虽然不一次性)阅读库参考以了解其中的内容。 - chepner

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]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接