How to find list intersection?

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

    A functional way can be achieved using filter and lambda operator.

    list1 = [1,2,3,4,5,6]
    
    list2 = [2,4,6,9,10]
    
    >>> list(filter(lambda x:x in list1, list2))
    
    [2, 4, 6]
    

    Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:

    >>> list(filter(lambda x:x not in list1, list2))
    [9,10]
    

    Edit2: python3 filter returns a filter object, encapsulating it with list returns the output list.

提交回复
热议问题