在Python中需要保留重复项时比较两个列表中的元素 [英] Comparing elements in two lists when keeping duplicates is desired in Python

查看:381
本文介绍了在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']

所以我希望输出是

c = ['hi']  

因为第一个列表中包含一个额外的"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.

我尝试过的事情涉及使用set运算符,它具有相同的结果,因为该运算将列表的成员减少为唯一.

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!

推荐答案

计数器对象支持多组操作:

>>> from collections import Counter
>>> a = ['hi', 'hi', 'bye', 'hi']
>>> b = ['hi', 'hi', 'bye']
>>> Counter(a) - Counter(b)
Counter({'hi': 1})

从柜台重建列表:

>>> list(counter.elements())
['hi']

这篇关于在Python中需要保留重复项时比较两个列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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