This is similar to some other questions (Explicitly select items from a Python list or tuple, Grabbing specific indices of a list in Python), but I'm looking to do the opposite:
What is a clean way to specify a list/tuple of indices to exclude, instead of to select? I'm thinking of something similar to R or MATLAB where you can specify indices to exclude, like:
vector1 <- c('a', 'b', 'c', 'd')
vector2 <- vector1[-1] # ['b', 'c', 'd']
vector3 <- vector1[c(-1, -2)] # ['c', 'd']
Is there a good way to accomplish the same thing in Python? Apologizes if this is a dupe, I wasn't sure exactly what to search for.
from operator import itemgetter def exclude (to_exclude, vector): "Exclude items with particular indices from a vector." to_keep = set (range (len (vector))) - set (to_exclude) return itemgetter (*to_keep) (vector) Thanks for contributing an answer to Stack Overflow!
The index/match formula in your original post is indicative of a lookup function, not a sum function. But, it still depends on whether you want to exclude the entries where the ID, Category, and Ctry match Sheet1, or exclude all entries on Sheet2 where the ID matches any of the ID's listed on Sheet1 regardless of Category and Ctry.
But it really doesn't matter much for just a handful; if you've already got a list or tuple with 4 indices in it, that's a " Set or Sequence " too, so you can just use it.) * Technically, any Container will do. But most Container s that aren't a Set or Sequence would be silly here.
>>> to_exclude = {1, 2}
>>> vector = ['a', 'b', 'c', 'd']
>>> vector2 = [element for i, element in enumerate(vector) if i not in to_exclude]
The tricks here are:
filter
function, especially if the predicate you're filtering on is already lying around as a function with a nice name.)enumerate
to get each element and its index together.in
operator against any Set
or Sequence
* type to decide which ones to filter. (A set
is most efficient if there are a lot of values, and probably conceptually the right answer… But it really doesn't matter much for just a handful; if you've already got a list or tuple with 4 indices in it, that's a "Set
or Sequence
" too, so you can just use it.)* Technically, any Container
will do. But most Container
s that aren't a Set
or Sequence
would be silly here.
import numpy
target_list = numpy.array(['1','b','c','d','e','f','g','h','i','j'])
to_exclude = [1,4,5]
print target_list[~numpy.in1d(range(len(target_list)),to_exclude)]
because numpy is fun
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