Home > Mobile >  Compare two list of sets
Compare two list of sets

Time:01-16

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. (no intersection)

In this case, {'a','b'} has no common elements in {'c','d','e'}.

  1. {'c','d'} has no common elements in {'e','f'}.
  2. {'a','b','c'} has common elements 'a' and 'b' in {'a','b','d'}.
  3. {'c','f'} has common elements 'c' and 'f' in {'c','f'}.

So list1[0] and list1[1] do not have the same element(s) in list2[0] and list2[1]

It will return a list of indices: 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.

CodePudding user response:

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]

CodePudding user response:

I found a solution, I'm using a dictionary to output the common letters for each set

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)
  •  Tags:  
  • Related