简体   繁体   English

删除列表中的匹配项

[英]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). 因此,我意识到主要的问题是,当我删除项目时,它会缩短列表,因此Python然后跳过了中间项目(非常烦人)。 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 : 最简单的方法是使用set来确定a 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 . a = i不复制列表,它只是设置另一个变量, i指向您的列表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 : 您还可以使用set来保证不重复,但不保留顺序

list(set(i))

Your statements a = i and c = a merely make new names that reference the same object. 您的语句a = ic = a仅使引用相同对象的新名称成为可能。 Then as you removed things from a , it's removed from b and i , since they are the same object. 然后,当您从a删除对象时,它们也会从bi删除,因为它们是同一对象。 You'll want to make copies of the lists instead, like so 您将需要复制列表,就像这样

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

In python, when you write this: 在python中,当您编写此代码时:

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 . 您创建一个对象(在本例中为列表),并将其分配给名称 i Your next line, a = i , tells the interpreter that the name a refers to the same Object. 您的下一行a = i告诉解释器, 名称 a指向相同的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. 您可以通过切片速记i[:]来做到这一点,也可以使用a = list(i)使其更明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM