Find intersection of two nested lists?

前端 未结 20 1129
星月不相逢
星月不相逢 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:47

    Simple way to find difference and intersection between iterables

    Use this method if repetition matters

    from collections import Counter
    
    def intersection(a, b):
        """
        Find the intersection of two iterables
    
        >>> intersection((1,2,3), (2,3,4))
        (2, 3)
    
        >>> intersection((1,2,3,3), (2,3,3,4))
        (2, 3, 3)
    
        >>> intersection((1,2,3,3), (2,3,4,4))
        (2, 3)
    
        >>> intersection((1,2,3,3), (2,3,4,4))
        (2, 3)
        """
        return tuple(n for n, count in (Counter(a) & Counter(b)).items() for _ in range(count))
    
    def difference(a, b):
        """
        Find the symmetric difference of two iterables
    
        >>> difference((1,2,3), (2,3,4))
        (1, 4)
    
        >>> difference((1,2,3,3), (2,3,4))
        (1, 3, 4)
    
        >>> difference((1,2,3,3), (2,3,4,4))
        (1, 3, 4, 4)
        """
        diff = lambda x, y: tuple(n for n, count in (Counter(x) - Counter(y)).items() for _ in range(count))
        return diff(a, b) + diff(b, a)
    

提交回复
热议问题