繁体   English   中英

两个列表的共同元素,包括重复

[英]Common elements of two lists including repetitions

我有两个列表:

a = ['item.1','item.2','item.3', 'another_item'] 
b = ['item.4','item.5', 'another_item']

我将元素拆分为最终

a = ['item', 'item', 'item', 'another_item']
b = ['item', 'item', 'another_item']

我想找到实际的共享项目,最后得到

c = ['item','item', 'another_item']

但是set(a).intersection(b)将返回我['item', 'another_item']

c = [x for x in list1 if x in list2]返回['item', 'item', 'item', 'another_item']

我的列表实际上是由其他出现多次的项目组成的,因此,我不能仅仅找出哪个列表包含“ item”出现次数最少的列表并对其进行迭代(如果它包含更多的“ another_item”出现次数)。 我还能尝试什么?

来自集合的 计数器能够处理多集合:

>>> from collections import Counter

>>> a = ['item', 'item', 'item', 'another_item']
>>> b = ['item', 'item', 'another_item']

# create counter objects for a and b
>>> ca = Counter(a)
>>> cb = Counter(b)

>>> intersection = ca & cb
>>> intersection
Counter({'item': 2, 'another_item': 1})

>>> list(intersection.elements())
['item', 'item', 'another_item']

您可以使用:

a = ['item','item','item', 'another_item']
b = ['item','item', 'another_item']
b, common = b[:], [ e for e in a if e in b and (b.pop(b.index(e)) or True)]
print(common) # ['item', 'item', 'another_item']

缺点是需要创建列表之一的副本,因为列表理解将必须删除迭代的项目。 但是,如果您切换a和b,它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM