How to find list intersection?

前端 未结 12 2472
别那么骄傲
别那么骄傲 2020-11-22 05:21
a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c

actual output: [1,3,5,6] expected output: [1,3,5]

How can we ac

12条回答
  •  借酒劲吻你
    2020-11-22 05:41

    You can also use a counter! It doesn't preserve the order, but it'll consider the duplicates:

    >>> from collections import Counter
    >>> a = [1,2,3,4,5]
    >>> b = [1,3,5,6]
    >>> d1, d2 = Counter(a), Counter(b)
    >>> c = [n for n in d1.keys() & d2.keys() for _ in range(min(d1[n], d2[n]))]
    >>> print(c)
    [1,3,5]
    

提交回复
热议问题