I have a list that looks like this:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
I'd like to generate a filtered list that looks like this:
filtered_lst = [2, 6, 7, 9, 10, 13]
Does Python provide a convention for custom slicing. Something such as:
lst[1, 5, 6, 8, 9, 12] # slice a list by index
So [::-1] means from 1st element to last element in steps of 1 in reverse order. If you have [start:stop] it's the same as step=1 .
Slicing is indexing syntax that extracts a portion from a list. If a is a list, then a[m:n] returns the portion of a : Starting with postion m. Up to but not including n. Negative indexing can also be used.
Use operator.itemgetter()
:
from operator import itemgetter
itemgetter(1, 5, 6, 8, 9, 12)(lst)
Demo:
>>> from operator import itemgetter
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> itemgetter(1, 5, 6, 8, 9, 12)(lst)
(2, 6, 7, 9, 10, 13)
This returns a tuple; cast to a list with list(itemgetter(...)(lst))
if a that is a requirement.
Note that this is the equivalent of a slice expression (lst[start:stop]
) with a set of indices instead of a range; it can not be used as a left-hand-side slice assignment (lst[start:stop] = some_iterable
).
Numpy arrays have this kind of slicing syntax:
In [45]: import numpy as np
In [46]: lst = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
In [47]: lst[[1, 5, 6, 8, 9, 12]]
Out[47]: array([ 2, 6, 7, 9, 10, 13])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With