python对比列表中的重复项-在Python中需要保留重复项时比较两个列表中的元素

I"d like to compare two lists. I"d like to find elements in the first list that don"t have a corresponding entry in the second list (order doesn"t matter):

a = ["hi", "hi", "bye", "hi"]

b = ["hi", "hi", "bye"]

So I would like the output to be

c = ["hi"]

since the first list has an extra "hi" in it that doesn"t appear in the second list.

If I do one of the usual techniques, I can use a list comprehension:

[x for x in a if x not in b]

which gives me [], which is not what I want.

Things I"ve tried involve using the set operator, which have the same outcome, since that operation reduces the members of the list to uniqueness.

This seems like a simple operation. Do I need to enumerate each element in the lists first, and create tuples to compare? Do I need to put them into a Counter dict? All this sounds a little bit like overkill when I just want to a simple comparison of the elements in a list!

解决方案

Counter objects support multi-set operations:

>>> from collections import Counter

>>> a = ["hi", "hi", "bye", "hi"]

>>> b = ["hi", "hi", "bye"]

>>> Counter(a) - Counter(b)

Counter({"hi": 1})

Rebuilding a list from the Counter:

>>> list(counter.elements())

["hi"]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值