1
org = [1,1,1,1,2,2,4]
remove = [1,1,2]

result = foo(org, remove)
# result = [1,1,2,4]
# two 1 are removed and one 2

I want to remove items from org, but not all with the same value - only one remove each item in the remove-array

Is there a numpy function to do so?

2
  • 3
    Turn the array into a count table? That would be more generally useful anyway Commented Nov 28, 2021 at 21:52
  • you arent actualy using numpy, for a list you can just do [org.remove(i) for i in remove]. Note that this will throw ValueError if i is not in org, so you need to handle that. Also @CJR has a point, I dont know what is the use case but consider it. Commented Nov 28, 2021 at 21:54

1 Answer 1

2

Following on from CJR's comment, it turns out that the built-in Counter understands subtraction and "does the right thing". It silently ignores any elements that aren't present in the first counter.

So you can do something like this:

from collections import Counter

c1 = Counter(org)
c2 = Counter(remove)
result = list((c1 - c2).elements())

To give result = [1,1,2,4].

Edit: Of course, this won't necessarily preserve the order. And if you know both collections are already sorted at the start anyway, there will be a more efficient approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.