简体   繁体   中英

python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both

Related to: Remove all the elements that occur in one list from another

I have listA [1, 1, 3, 5, 5, 5, 7] and listB [1, 2, 5, 5, 7] and I want to subtract occurrences of items from listA. The result should be a new list: [1, 3, 5] Note:

  1. 1 had 2 occurrences in listA and once in listB, now it appears 2-1=1 times
  2. 2 did not appear in listA, so nothing happens
  3. 3 stays with 1 occurrence, as its not in listB
  4. 5 occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times
  5. 7 occurred once in listA and once in listB, so now it will appear 1-1=0 times

Does this make sense?

Here is a non list comprehension version for those new to Python

listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
for i in listB:
    if i in listA:
        listA.remove(i)

print listA

In cases like these a list comprehension should always be used:

listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]

newList = [i for i in listA if i not in listB or listB.remove(i)]

print (newList)

Here are the results:

[1, 3, 5]

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