找到两个嵌套列表的交集?

我知道如何获得两个平面列表的交集:

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]

要么

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

print intersect(b1, b2)

但是当我必须找到嵌套列表的交集时,我的问题就开始了:

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

你们能帮我一把吗?

有关

  • 在python中展平浅表

  • 如果你想:

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

    那么这里是你的Python 2的解决方案:

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

    在Python 3中, filter返回一个迭代而不是list ,所以你需要用list()包装filter调用:

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

    说明:

    过滤器部分获取每个子列表的项目并检查它是否在源列表c1中。 列表理解是针对c2中的每个子列表执行的。


    你不需要定义交集。 它已经是集合中的头等部分。

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

    对于希望找到两个列表的交集的人来说,Asker提供了两种方法:

    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]
    

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

    但是有一种更高效的混合方法,因为你只需要在list / set之间进行一次转换,而不是三次转换:

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

    这将在O(n)中运行,而他涉及列表理解的原始方法将运行在O(n ^ 2)

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

    上一篇: Find intersection of two nested lists?

    下一篇: Trilateration of a signal using Time Difference(TDOA)