简体   繁体   中英

Removing common elements from lists

With these lists:

a=[2,6,79,10]
b=[6,7,2,0,8,5]

The desired output would be:

a=[79,10]
b=[7,0,8,5]

Why is this code not working?

def cel(a,b):
    for x in a:
        if x in b:
            b.remove(x)
            a.remove(x)

you can use set operations for this purpose:

i = set(a).intersection(set(b))
a = list(set(a).difference(i))
b = list(set(b).difference(i))

EDIT I tried to debug your original code and realized that it skips a number whenever it removes one. After googling I found that modifying a list while iterating is not a defined behavior because of some internal indexing issues. The easiest workaround would be using a copy of the original array in your for loop as:

for x in a[:]:
    if x in b:
        b.remove(x)
        a.remove(x)

The algorithm in the @gokcehan's answer that preserve order is cubic O(n**3) . It is very inefficient even for lists of moderate sizes (Programming Pearls book has an example where a linear algorithm in Basic outperforms cubic algorithm in C (minutes vs. days)).

You can preserve order and run it in linear time:

common = set(a).intersection(b)
a = [x for x in a if x not in common]
b = [x for x in b if x not in common]

You can do it inplace:

def remove_items(lst, items):
    items = set(items) # unnecessary in your case
    pos = 0
    for x in lst:
        if x not in items:
           lst[pos] = x # save
           pos += 1
    del lst[pos:]

common = set(a).intersection(b)
remove_items(a, common)
remove_items(b, common)

demo

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