简体   繁体   中英

Remove common elements in two lists [python]

I want to remove the common elements between two lists. I mean something like this

name1 = ['m','a','d','d','y']

name2 = ['m','a','d','h','a','v','a','n']

#output be like

output = ['d','y','h','a','v','a','n']

You can do like:

import itertools

name1 = ['m','a','d','d','y']

name2 = ['m','a','d','h','a','v','a','n']

output = list(itertools.chain.from_iterable(zip(*[(x, y) for x, y in zip(name1, name2) if x != y]))) + (name2 if len(name2) > len(name1) else name1)[min(len(name1), len(name2)):]

print(output)

OUTPUT

['d', 'y', 'h', 'a', 'v', 'a', 'n']
  • The list comprehension [(x, y) for x, y in zip(name1, name2) if x != y] simply compares the list character by character and stores the mismatching pairs as tuples;
  • zip(* makes sure that the resulting tuples are reordered in the desired sequence (from [('d', 'h'), ('y', 'a')] for [('d', 'y'), ('h', 'a')] ;
  • list(itertools.chain.from_iterable concatenates the tuples in one list;
  • (name2 if len(name2) > len(name1) else name1)[min(len(name1), len(name2)):] takes the longest list and select the residual elements which have not been compared so far, attaching it to the list obtained in the previous point.

If order doesn't matter, you can use collections.Counter and a list comprehension:

from collections import Counter
counts = (Counter(name1) - Counter(name2)) + (Counter(name2) - Counter(name1))
out = [i for x,y in counts.items() for i in [x]*y]

Output:

['d', 'y', 'a', 'a', 'h', 'v', 'n']

Probably the simplest and most obvious way is to do it manually.

Example:

hi = min(len(name1), len(name2)) - 1 # last element of the shorter list

while hi >= 0:                  # iterate backwards to avoid bugs
    if name1[hi] == name2[hi]:  # check if the items in both lists are equal
        del name1[hi]           # if they are the same then delete 
        del name2[hi]           # from both lists
    hi -= 1                     # then do the same for the rest 
output = name1 + name2          # Finally merge two lists into 1

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