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?
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.
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!
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