Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple elements from a list of index with Python

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

This is my solution, but I don't like the implementation as it requires to import packages, doesn't work when the values contain maxint, and iterate over the values multiple 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?

like image 848
prosseek Avatar asked Apr 10 '15 22:04

prosseek


2 Answers

This should work:

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

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

like image 150
orlp Avatar answered Oct 13 '22 00:10

orlp


Here's a version that only uses built in list methods.

It's fairly naive so there might be solutions that are way faster, but does not need additional packages etc, which might be what you 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 that would like to suggest edits/optimizations with this feel free.

EDIT

I tried to use the timeit functions on both the fancy and my naive implementations, they are not conclusive but one doesn't seem faster than the other. This is done manually in the interpreter, though. Couldn't get a script working. As far as performance goes they don't differ by much. I wouldn't mind if someone else can prove me wrong though!

like image 28
matrixanomaly Avatar answered Oct 13 '22 00:10

matrixanomaly