How to find list intersection?

前端 未结 12 2264
别那么骄傲
别那么骄傲 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]
    
    0 讨论(0)
  • 2020-11-22 05:44

    It might be late but I just thought I should share for the case where you are required to do it manually (show working - haha) OR when you need all elements to appear as many times as possible or when you also need it to be unique.

    Kindly note that tests have also been written for it.

    
    
        from nose.tools import assert_equal
    
        '''
        Given two lists, print out the list of overlapping elements
        '''
    
        def overlap(l_a, l_b):
            '''
            compare the two lists l_a and l_b and return the overlapping
            elements (intersecting) between the two
            '''
    
            #edge case is when they are the same lists
            if l_a == l_b:
                return [] #no overlapping elements
    
            output = []
    
            if len(l_a) == len(l_b):
                for i in range(l_a): #same length so either one applies
                    if l_a[i] in l_b:
                        output.append(l_a[i])
    
                #found all by now
                #return output #if repetition does not matter
                return list(set(output))
    
            else:
                #find the smallest and largest lists and go with that
                sm = l_a if len(l_a)  len(l_b) else l_b
    
                for i in range(len(sm)):
                    if sm[i] in lg:
                        output.append(sm[i])
    
                #return output #if repetition does not matter
                return list(set(output))
    
        ## Test the Above Implementation
    
        a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
        b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        exp = [1, 2, 3, 5, 8, 13]
    
        c = [4, 4, 5, 6]
        d = [5, 7, 4, 8 ,6 ] #assuming it is not ordered
        exp2 = [4, 5, 6]
    
        class TestOverlap(object):
    
            def test(self, sol):
                t = sol(a, b)
                assert_equal(t, exp)
                print('Comparing the two lists produces')
                print(t)
    
                t = sol(c, d)
                assert_equal(t, exp2)
                print('Comparing the two lists produces')
                print(t)
    
                print('All Tests Passed!!')
    
        t = TestOverlap()
        t.test(overlap)
    
    
    0 讨论(0)
  • 2020-11-22 05:45

    This way you get the intersection of two lists and also get the common duplicates.

    >>> from collections import Counter
    >>> a = Counter([1,2,3,4,5])
    >>> b = Counter([1,3,5,6])
    >>> a &= b
    >>> list(a.elements())
    [1, 3, 5]
    
    0 讨论(0)
  • 2020-11-22 05:46
    a = [1,2,3,4,5]
    b = [1,3,5,6]
    c = list(set(a).intersection(set(b)))
    

    Should work like a dream. And, if you can, use sets instead of lists to avoid all this type changing!

    0 讨论(0)
  • 2020-11-22 05:55

    If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using intersection():

    a = [1,2,3,4,5]
    b = [1,3,5,6]
    set(a).intersection(b)
    
    0 讨论(0)
  • 2020-11-22 05:55

    This is an example when you need Each element in the result should appear as many times as it shows in both arrays.

    def intersection(nums1, nums2):
        #example:
        #nums1 = [1,2,2,1]
        #nums2 = [2,2]
        #output = [2,2]
        #find first 2 and remove from target, continue iterating
    
        target, iterate = [nums1, nums2] if len(nums2) >= len(nums1) else [nums2, nums1] #iterate will look into target
    
        if len(target) == 0:
                return []
    
        i = 0
        store = []
        while i < len(iterate):
    
             element = iterate[i]
    
             if element in target:
                   store.append(element)
                   target.remove(element)
    
             i += 1
    
    
        return store
    
    0 讨论(0)
提交回复
热议问题