简体   繁体   English

比较两个集合列表

[英]Compare two list of sets

For example, I have two list of sets:例如,我有两个集合列表:

list1 = [{'a','b'}, {'c','d'}, {'a','b','c'}, {'c','f'}]
list2 = [{'c','d','e'}, {'e','f'}, {'a','b','d'}, {'c','f'}]

I need to output a list of indices where list1[i] and list2[i] don't share common elements.我需要 output 一个索引列表,其中 list1[i] 和 list2[i] 不共享共同元素。 (no intersection) (没有交叉口)

In this case, {'a','b'} has no common elements in {'c','d','e'} .在这种情况下, {'a','b'}{'c','d','e'}中没有公共元素。

  1. {'c','d'} has no common elements in {'e','f'} . {'c','d'}{'e','f'}中没有公共元素。
  2. {'a','b','c'} has common elements 'a' and 'b' in {'a','b','d'} . {'a','b','c'}{'a','b','d'} } 中有共同的元素'a''b'
  3. {'c','f'} has common elements 'c' and 'f' in {'c','f'} . {'c','f'}中有共同的元素'c''f' {'c','f'}

So list1[0] and list1[1] do not have the same element(s) in list2[0] and list2[1]所以list1[0]list1[1]list2[0]list2[1]中没有相同的元素

It will return a list of indices: list = [0,1]它将返回一个索引列表: list = [0,1]

My approach is:我的做法是:

for l1,l2 in zip(list1,list2):
    for i in l1:
        if i in l2:
            print(i)

This is clearly not correct.这显然是不正确的。 Any help is appreciated.任何帮助表示赞赏。

You can enumerate over the zipped lists and filter the indices based on whether the pair of sets is disjoint :您可以枚举压缩列表并根据这对集合是否不相交来过滤索引:

list1 = [{'a','b'}, {'c','d'}, {'a','b','c'}, {'c','f'}]
list2 = [{'c','d','e'}, {'e','f'}, {'a','b','d'}, {'c','f'}]

indices = [i for i, (a, b) in enumerate(zip(list1, list2)) if a.isdisjoint(b)]

# [0, 1]

I found a solution, I'm using a dictionary to output the common letters for each set我找到了一个解决方案,我正在使用字典来 output 每个集合的常用字母

iter = [i for i in range(len(list1))]
list3 = []
dict = {}
for i in iter:
    for l1, l2 in zip(list1[i], list2[i]):
        letter = ""
        if l1 not in list2[i]:
            letter += l1
        if l2 not in list1[i]:
            letter += l2
        if letter != '':
        dict[f'Index  {str(i)}'] = letter
print(dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM