在Python中抓取列表的特定索引

sih*_*hrc 3 python indexing list python-2.7

有没有办法获取列表的特定索引,就像我在NumPy中可以做的那样?

sample = ['a','b','c','d','e','f']
print sample[0,3,5]
>>>['a','d','f']
Run Code Online (Sandbox Code Playgroud)

我试过谷歌搜索这个,但我找不到一个好方法来说出导致相关结果的问题......

Ter*_*ryA 9

您可以使用列表理解:

>>> sample = ['a','b','c','d','e','f']
>>> [sample[i] for i in (0, 3, 5)]
['a', 'd', 'f']
Run Code Online (Sandbox Code Playgroud)

或者,我很快就做了些什么:

>>> class MyList(list):
...     def __getitem__(self, *args):
...             return [list.__getitem__(self, i) for i in args[0]]
... 
>>> mine = MyList(['a','b','c','d','e','f'])
>>> print mine[0, 3, 5]
['a', 'd', 'f']
Run Code Online (Sandbox Code Playgroud)