Python从列表中删除存在于另一个列表中的项目,但保留不在该相交处的重复项 [英] Python removing items from a list that exist in another list but keeping duplicates that aren't in that intersect

查看:249
本文介绍了Python从列表中删除存在于另一个列表中的项目,但保留不在该相交处的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python尝试从另一个列表中删除相交的项目.所以下面是我所拥有的.

I'm using python to try and remove items that intersection from another list. So below is what I have.

letter = ['a', 'a', 'i', 'd', 'e', 'i', 'a', 'b', 'b', 'c', 'o', 'g', 'a', 'f', 'f', 'i', 'g', 'i' ]
cons = ['b','c','d', 'f', 'g']

,我想要从字母列表中删除缺点"列表中的任何字母,但保留其他所有内容.所以下面是我想要得到的.

and what I want is to remove any letter in the cons list from the letter list but preserve everything else. So below is what I want to get.

 letter = ['a', 'a', 'i', 'e', 'i', 'a', 'o', 'a', i', 'i' ]

以下是我到目前为止尝试过的方法,但是没有用.

Below is what I have tried so far but it's not working.

for i in letter[:]:
    if i in cons: 
         letter.remove(i)
         cons.remove(i)

和...

list(set(x) - set(y))

我只想删除列表的交集,并保留第一个列表中未包含在第二个列表中的重复项.到目前为止,我尝试过的所有操作都从我要保留的第一个列表中删除了这些重复项.任何帮助,我们将不胜感激!

I just want to remove the intersection of the lists and keep the duplicates from the first list that are not in the second list. Everything I've tried so far has removed those duplicates from the first list that I want to keep. Any help is greatly appreciated!

推荐答案

>>> letter = ['a', 'a', 'i', 'd', 'e', 'i', 'a', 'b', 'b', 'c', 'o', 'g', 'a', 'f', 'f', 'i', 'g', 'i' ]
>>> cons = ['b','c','d', 'f', 'g']

>>> [x for x in letter if x not in cons]
['a', 'a', 'i', 'e', 'i', 'a', 'o', 'a', 'i', 'i']

一个简单的列表理解会成功吗?

a simple list comprehension will do the trick?

正如ShadowRanger所说,将缺点转换为一组将提高性能(主要是用于比这些更大的数据集):

As ShadowRanger said, it would improve performance (mostly for larger data sets than these) to convert cons to a set:

cons = set(cons)

然后进入列表comp.这样做会更好,因为sets被散列并使得以更快的方式获取项目/检查项目

then to go into the list comp. This is better because sets are hashed and makes getting items/checking for items in it way faster

这篇关于Python从列表中删除存在于另一个列表中的项目,但保留不在该相交处的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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