Python删除列表的重叠 [英] Python removing overlap of lists

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

问题描述

我知道已经问过这个问题的变体了,但是我找不到能解决我的特定目的的

I'm aware variations of this question have been asked already, but none of the ones I've been able to find have addressed my specific aim.

我试图在Python中获取两个带有字符串元素的列表,并删除两者的重叠部分.例如:

I am trying to take two lists in Python with string elements and remove the overlapping sections of the two. For example:

list1 = ["25","+","7","*","6","/","7"]
list2 = ["7","*","6"]

应该去

["25","+","/","7"]

我考虑了

[i for i in list1 if not in list2]

但这会产生

["25","+","/"]

因为两个"7"的实例都将被删除.

as both instances of "7" would be taken out.

我如何才能在这里实现自己的目标?谢谢.

How can I achieve what I'm trying to do here? Thanks.

编辑-这被标记为可能重复.在我的列表理解示例中,我已经解释了与链接的链接列表是一个不同的问题.

Edit - this was marked as a possible duplicate. In my example with the list comprehension, I already explained how it is a different problem to the one linked.

推荐答案

本质上,您希望对多件套(例如包)进行差异操作. Python为collections.Counter对象实现了此:

Essentially, you want a difference operation on a multi-set, i.e. a bag. Python implements this for the collections.Counter object:

提供了几种数学运算来组合Counter 对象以产生多重集(计数大于 零).加减法将计数器相加或相加 减去相应元素的数量.交叉口和 union返回相应计数的最小值和最大值.每个 操作可以接受带符号计数的输入,但是输出将 排除计数为零或更少的结果.

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

例如,

>>> list1 = ["25","+","7","*","6","/","7"]
>>> list2 = ["7","*","6"]
>>> list((Counter(list1) - Counter(list2)).elements())
['25', '+', '7', '/']

在Python 3.6及更高版本中,这将是有序的(尽管目前尚不能保证,可能应该将其视为实现细节).如果订单很重要,并且您没有使用此版本,则可能必须实现有序计数器.

In Python 3.6+ this will be ordered (although this is not currently guaranteed, and should probably be considered an implementation detail). If order is important, and you are not using this version, you may have to implement an ordered counter.

确实,文档本身提供了食谱:

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict):
...     'Counter that remembers the order elements are first encountered'
...     def __repr__(self):
...         return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
...     def __reduce__(self):
...         return self.__class__, (OrderedDict(self),)
...
>>> list((OrderedCounter(list1) - OrderedCounter(list2)).elements())
['25', '+', '/', '7']

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

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