代码之家  ›  专栏  ›  技术社区  ›  Baz

确定集合列表是否共享数据

  •  2
  • Baz  · 技术社区  · 7 年前

    给定一个集合列表,如何测试所有集合是否都不共享数据:

    例如:

    [set((1,2)),set((3,)),set((4,)),set((5,))] would be True
    

    但是

    [set((1,2)),set((2,)),set((4,)),set((5,))] would be False
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   javidcf    7 年前

    一种快速的方法是将集合的大小相加,并将其与并集的大小进行比较:

    def no_common_elements(sets):
        return sum(len(s) for s in sets) == len(set.union(*sets))
    
    print(no_common_elements([set((1, 2)), set((3,)), set((4,)), set((5,))]))
    # True
    print(no_common_elements([set((1, 2)), set((2,)), set((4,)), set((5,))]))
    # False
    
        2
  •  1
  •   jpp    7 年前

    你可以用 set.isdisjoint 具有 itertools.combinations :

    from itertools import combinations
    
    L1 = [set((1,2)),set((3,)),set((4,)),set((5,))]
    L2 = [set((1,2)),set((2,)),set((4,)),set((5,))]
    
    def test_all_disjoint(L):
        return all(x.isdisjoint(y) for x, y in combinations(L, 2))
    
    test_all_disjoint(L1)  # True
    test_all_disjoint(L2)  # False
    

    你可以看到 performance benefits 使用 设置isdisjoint 结束 set.union / set.intersection .

        3
  •  1
  •   jeschwar    7 年前

    下面是一个使用 numpy pandas :

    import numpy as np
    import pandas as pd
    
    
    def shares_no_data(list_of_sets):
        # convert the list of sets into a 1d numpy array
        array = np.hstack(list(map(list, list_of_sets)))
    
        # no data will be shared if we have the same number of unique values 
        # as the number of items in the array
        return len(pd.unique(array)) == len(array)
    

    我们可以用以下方法进行测试:

    l1 = [set((1,2)),set((3,)),set((4,)),set((5,))]
    l2 = [set((1,2)),set((2,)),set((4,)),set((5,))]
    
    shares_no_data(l1)
    # returns True
    
    shares_no_data(l2)
    # returns False