Python list intersection with non unique items

后端 未结 2 1959
星月不相逢
星月不相逢 2020-12-03 11:46

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)         


        
2条回答
  •  借酒劲吻你
    2020-12-03 11:56

    Use collections.Counter for each word and use these as sets:

    >>> from collections import Counter
    >>> str_a, str_b = 'aabbcc', 'aabd'
    >>> Counter(str_a) & Counter(str_b)
    Counter({'a': 2, 'b': 1})
    >>> ''.join((Counter(str_a) & Counter(str_b)).elements())
    'aab'
    

    The Counter is a dict subclass, but one that counts all the elements of a sequence you initialize it with. Thus, "aabbcc" becomes Counter({'a': 2, 'b': 2, 'c': 2}).

    Counters act like multisets, in that when you use 2 in an intersection like above, their counts are set to the mimimum values found in either counter, ignoring anything whose count drops to 0. If you were to compute their union, the maximum counts would be used instead.

提交回复
热议问题