简体   繁体   中英

substract items from array / numpy

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM