python从2个列表中删除重复项 [英] python remove duplicates from 2 lists

查看:987
本文介绍了python从2个列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从2个列表中删除重复项。所以我写了这个功能:

I am trying to remove duplicates from 2 lists. so I wrote this function:

a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]

b = ["ijk", "lmn", "opq", "rst", "123", "456", ]

for i in b:
    if i in a:
        print "found " + i
        b.remove(i)

print b

但是,我发现匹配项后面的匹配项目不会被删除。

But I find that the matching items following a matched item does not get remove.

我得到这样的结果:

found ijk
found opq
['lmn', 'rst', '123', '456']

但我预计结果像这样:

['123','456']

['123', '456']

如何修复我的功能我想要什么?

How can I fix my function to do what I want?

谢谢。

推荐答案

继续假设你有这个列表:

Here is what's going on. Suppose you have this list:

['a', 'b', 'c', 'd']

您正在循环列表中的每个元素。假设你目前在索引位置1:

and you are looping over every element in the list. Suppose you are currently at index position 1:

['a', 'b', 'c', 'd']
       ^
       |
   index = 1

...并删除索引位置1的元素,给出你这样:

...and you remove the element at index position 1, giving you this:

['a',      'c', 'd']
       ^
       |
    index 1

删除该项后,其他项目向左滑动,给您这是:

After removing the item, the other items slide to the left, giving you this:

['a', 'c', 'd']
       ^
       |
    index 1

然后当循环再次运行时,循环将索引增加到2,给你这个:

Then when the loop runs again, the loop increments the index to 2, giving you this:

['a', 'c', 'd']
            ^ 
            |
         index = 2

看看你如何跳过'c'?课程是:永远不要从您正在循环的列表中删除一个元素。

See how you skipped over 'c'? The lesson is: never delete an element from a list that you are looping over.

这篇关于python从2个列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆