Find intersection of two nested lists?

前端 未结 20 1580
星月不相逢
星月不相逢 2020-11-22 04:16

I know how to get an intersection of two flat lists:

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]

or

<
20条回答
  •  天命终不由人
    2020-11-22 04:58

    I don't know if I am late in answering your question. After reading your question I came up with a function intersect() that can work on both list and nested list. I used recursion to define this function, it is very intuitive. Hope it is what you are looking for:

    def intersect(a, b):
        result=[]
        for i in b:
            if isinstance(i,list):
                result.append(intersect(a,i))
            else:
                if i in a:
                     result.append(i)
        return result
    

    Example:

    >>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
    >>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
    >>> print intersect(c1,c2)
    [[13, 32], [7, 13, 28], [1, 6]]
    
    >>> b1 = [1,2,3,4,5,9,11,15]
    >>> b2 = [4,5,6,7,8]
    >>> print intersect(b1,b2)
    [4, 5]
    

提交回复
热议问题