抓取列表的特定索引 [英] Grabbing specific indices of a list
本文介绍了抓取列表的特定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法像我在NumPy中所做的那样获取列表的特定索引?
Is there a way to grab specific indices of a list, much like what I can do in NumPy?
sample = ['a','b','c','d','e','f']
print sample[0,3,5]
>>>['a','d','f']
我已经尝试使用Google搜索,但是找不到找到相关结果的好措辞...
I've tried Googling this, but I couldn't find a good way to word my issue that resulted in relevant results...
推荐答案
您可以使用列表理解:
>>> sample = ['a','b','c','d','e','f']
>>> [sample[i] for i in (0, 3, 5)]
['a', 'd', 'f']
或者,我很快做出了一些事情:
Or, something I quickly made:
>>> 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']
这篇关于抓取列表的特定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文