简体   繁体   中英

Python subtract list of strings from another list of strings

I would like to subtract a list of strings where there are more than one element of the same (so set operations are not useful).

Example:

C = ['A','B','B']
D = ['B']

I would like a way to do so that:

C - D = ['A','B']

Example of what I got so far, but does not give the result I want

[item for item in C if item not in D]
returns: ['A']

C = ['A','B', 'A','A','B','B','B','X','B']

D = ['A','B','B','Y']

This is what I want the result to be:

C - D = ['A', 'A', 'B', 'B','B','X']

You can use Counter from collections:

from collections import Counter
C_D = [i for v,c in (Counter(C)-Counter(D)).items() for i in v*c] 

Though Alain T.'s way is okay, there is a better way using Counter :

from collections import Counter
C = ['A','B','B']
D = ['B']
result = list((Counter(C) - Counter(D)).elements())

Without using any libraries:

output = [x for x in C if not x in D or D.remove(x)]

//output: ['A', 'B']

You can try this:

C = ['A','B', 'A','A','B','B','B','X','B']
D = ['A','B','B','Y']

res = [ i for i in C ]

for i in D:
  if i in C:
    res.remove(i)

print(res)
C = ['A','B','B']         
D = ['B']         
for char in D:
    if char in C:
       duplicate = C.remove(char)
print(duplicate)

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