问题
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