Indexing with List of Indices to Exclude
>>> 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:
- Use a list comprehension to transform one list into another. (You can also use the
filter
function, especially if the predicate you're filtering on is already lying around as a function with a nice name.) - Use
enumerate
to get each element and its index together. - Use the
in
operator against anySet
orSequence
* type to decide which ones to filter. (Aset
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
orSequence
" 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.
Use np.delete
In [38]: a
Out[38]: array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
In [39]: b
Out[39]: [3, 4, 5, 9]
In [40]: a[b]
Out[40]: array([ 7, 8, 9, 13])
In [41]: np.delete(a, b)
Out[41]: array([ 4, 5, 6, 10, 11, 12])
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