有没有办法获取列表的特定索引,就像我在NumPy中可以做的那样?
sample = ['a','b','c','d','e','f']
print sample[0,3,5]
>>>['a','d','f']
我尝试使用谷歌搜索,但我找不到一个好方法来说出导致相关结果的问题......
答案 0 :(得分:9)
您可以使用列表理解:
>>> sample = ['a','b','c','d','e','f']
>>> [sample[i] for i in (0, 3, 5)]
['a', 'd', 'f']
或者,我很快就做了一些事情:
>>> 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']