Removing multiple items from an index list using Python

I have a list of values ​​and a list of indexes, and I need to remove the elements that the indexes point to.

This is my solution, but I do not like the implementation, since I need to import packages, it does not work when the values ​​contain maxint and repeat the values ​​several times.

def remove_abnormalities(values, indices): v = list(values) for i in indices: v[i] = sys.maxint return filter(lambda i: i != sys.maxint, v) 

Any better solutions?

+5
source share
2 answers

This should work:

 def remove_abnormalities(values, indices): return [val for i, val in enumerate(values) if i not in indices] 

Alternatively, you can turn indices into a set before filtering for greater performance if the number of indices is large.

+8
source

Here is a version that uses only the built-in list methods.

This is rather naive, therefore there may be solutions that are faster, but do not need additional packages, etc., that you may need.

 def remove_abnormalities(values, indices): list = [] for i in range(len(values)): if i not in indices: list.append(values[i]) return list print(remove_abnormalities(["A","B","C","D","E","F","G","H"],[1,3,5])) #output is ['A', 'C', 'E', 'G', 'H'] 

If there are other Python gurus who would like to suggest changes / optimizations with this, no problem.

EDIT

I tried to use the timeit functions timeit both fantasy and my naive implementations, they are not final, but they do not seem faster than others. However, this is done manually in the interpreter. Failed to get the script working. In terms of performance, they are not much different. I would not mind if someone else can prove to me that it is wrong!

+1
source

All Articles