Grabbing specific indices of a list [duplicate]

本小妞迷上赌 提交于 2020-01-02 08:03:56

问题


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']

I've tried Googling this, but I couldn't find a good way to word my issue that resulted in relevant results...


回答1:


You can use a list comprehension:

>>> 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']


来源:https://stackoverflow.com/questions/17904791/grabbing-specific-indices-of-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!