简体   繁体   中英

Remove matching items in a list

Sorry if this is a duplicate question, I searched and couldn't find anything to help.

I'm currently trying to compare two lists. If there are any matching items I will remove them all from one of the lists.

However the results I have are buggy. Here is a rough but accurate representation of the method I'm using:

>>> i = [1,2,3,4,5,6,7,8,9]
>>> a = i
>>> c = a
>>> for b in c:
    if b in i:
        a.remove(b)


>>> a
[2, 4, 6, 8]
>>> c
[2, 4, 6, 8]

So I realised that the main issue is that as I remove items it shortens the list, so Python then skips over the intermediate item (seriously annoying). As a result I made a third list to act as an intermediate that can be looped over.

What really baffles me is that this list seems to change also even when I haven't directly asked it to!

The easiest way to do this is use a set to determine shared items in a and b :

for x in set(a).intersection(b):
    a.remove(x)

a = i Doesn't make a copy of a list, it just sets another variable, i to point at your list a . Try something like this:

>>> i = [1, 2, 3, 2, 5, 6]
>>> s = []
>>> for i in t:
       if i not in s:
          s.append(i)
>>> s
[1, 2, 3, 5, 6]

You can also use set which guarantees no duplicates, but doesn't preserve the order :

list(set(i))

Your statements a = i and c = a merely make new names that reference the same object. Then as you removed things from a , it's removed from b and i , since they are the same object. You'll want to make copies of the lists instead, like so

a = i[:]
c = a[:]

In python, when you write this:

i = [1,2,3,4,5,6,7,8,9]

You create an Object (in this case, a list) and you assign it to the name i . Your next line, a = i , tells the interpreter that the name a refers to the same Object. If you want them to be separate Object you need to copy the original list. You can do that via the slicing shorthand, i[:] , or you can use a = list(i) to be more explicit.

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