Find intersection of two nested lists?

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

def intersect(a, b):
    return list(set(a) & set(b))

print intersect(b1, b2)

But when I have to find intersection for nested lists then my problems starts:

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]]

In the end I would like to receive:

c3 = [[13,32],[7,13,28],[1,6]]

Can you guys give me a hand with this?

Related

  • Flattening a shallow list in python

  • If you want:

    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]]
    c3 = [[13, 32], [7, 13, 28], [1,6]]
    

    Then here is your solution for Python 2:

    c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
    

    In Python 3 filter returns an iterable instead of list , so you need to wrap filter calls with list() :

    c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
    

    Explanation:

    The filter part takes each sublist's item and checks to see if it is in the source list c1. The list comprehension is executed for each sublist in c2.


    You don't need to define intersection. It's already a first-class part of set.

    >>> b1 = [1,2,3,4,5,9,11,15]
    >>> b2 = [4,5,6,7,8]
    >>> set(b1).intersection(b2)
    set([4, 5])
    

    For people just looking to find the intersection of two lists, the Asker provided two methods:

    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]
    

    and

    def intersect(a, b):
         return list(set(a) & set(b))
    
    print intersect(b1, b2)
    

    But there is a hybrid method that is more efficient, because you only have to do one conversion between list/set, as opposed to three:

    b1 = [1,2,3,4,5]
    b2 = [3,4,5,6]
    s2 = set(b2)
    b3 = [val for val in b1 if val in s2]
    

    This will run in O(n), whereas his original method involving list comprehension will run in O(n^2)

    链接地址: http://www.djcxy.com/p/84922.html

    上一篇: 3D平面算法中点与线的最小垂直距离

    下一篇: 找到两个嵌套列表的交集?