Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: subsetting multiple elements

Tags:

python

Given

mylist = ["a", "b", "c"]

how can I subset elements 0 and 2 (i.e., ["a", "c"])?

like image 543
Mark Avatar asked Sep 01 '26 23:09

Mark


2 Answers

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']
like image 87
John La Rooy Avatar answered Sep 03 '26 15:09

John La Rooy


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')
like image 22
SiggyF Avatar answered Sep 03 '26 14:09

SiggyF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!