How to find list intersection?

前端 未结 12 2414
别那么骄傲
别那么骄傲 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: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
    

提交回复
热议问题