带有非唯一项的Python列表交集 [英] Python list intersection with non unique items

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

问题描述

我有两个字符串,我想在它们上有交点,包括重复项:

I have two strings and I would like to have the intersection on them including duplicate items:

str_a = "aabbcc"
str_b = "aabd"

list(set(str_a) & set(str_b))
>> "ab"

我希望它返回:

>> "aab"

有什么想法吗?

推荐答案

多集在python 2.7或更高版本中作为(可变)Counter对象实现.您可以对集合执行许多相同的操作,例如并集,交集,差(尽管计数可能变为负数)等:

Multisets are implemented in python 2.7 or later as (mutable) Counter objects. You can perform many of the same operations as you can for sets, such as union, intersection, difference (though counts can become negative), etc.:

from collections import Counter as mset

解决方案:

(mset("aabbcc") & mset("aabd")).elements()

更多详细信息:

>>> intersection = mset("aabbcc") & mset("aabd")
Counter({'a': 2, 'b': 1})

>>> list(intersection.elements())
['a', 'a', 'b']

>>> ''.join(intersection.elements())
'aab'

如果需要字符串,可以使用''.join,如果需要列表,可以使用list(),尽管我只是将其保留为intersection.elements()的可迭代格式.

You can use ''.join if you want a string, or list() if you want a list, though I would just keep it in iterable format as intersection.elements().

这篇关于带有非唯一项的Python列表交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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