Given
mylist = ["a", "b", "c"]
how can I subset elements 0 and 2 (i.e., ["a", "c"])?
Given
mylist = ["a", "b", "c"]
how can I subset elements 0 and 2 (i.e., ["a", "c"])?
Although this is not the usual way to use itemgetter,
>>> from operator import itemgetter
>>> mylist = ["a", "b", "c"]
>>> itemgetter(0,2)(mylist)
('a', 'c')
If the indices are already in a list - use *
to unpack it
>>> itemgetter(*[0,2])(mylist)
('a', 'c')
You an also use a list comprehension
>>> [mylist[idx] for idx in [0,2]]
['a', 'c']
or use map
>>> map(mylist.__getitem__, [0,2])
['a', 'c']
For fancy indexing you can use numpy arrays.
>>> mylist = ["a", "b", "c"]
>>> import numpy
>>> myarray = numpy.array(mylist)
>>> myarray
array(['a', 'b', 'c'],
dtype='|S1')
>>> myarray[[0,2]]
array(['a', 'c'],
dtype='|S1')