Home > front end >  find non common elements in two list of lists
find non common elements in two list of lists

Time:04-09

I have two lists of lists like:

A = [[1,2,3],[1,5],[7],[8,9,10],[11]]
B = [[11,2,2],[9,11],[6,14], [17]]

and I would like to only extract sublists which don't have any element in common with the other list of lists, so in my case the result would be:

res = [[1,5],[7],[6,14],[17]

I would also like to extend the formula to more than 2 list of lists, if possible. I cannot find an easy way to do it, so that if I added another list of lists as in the example:

A = [[1,2,3],[1,5],[7],[8,9,10],[11]]
B = [[11,2,2],[9,11],[6,14], [17]]
C = [[17,18,19], [14,10],[100,101]]

than the result is:

res = [[1,5],[7],[100,101]]

CodePudding user response:

We could check the intersection between the union of sublists in B and each sublist in A (do the same job for each sublist in B and the union of sublists in A), then concatenate the resulting lists:

res = ([s_lst for s_lst in A if not set(s_lst).intersection(set().union(*B))] 
         [s_lst for s_lst in B if not set(s_lst).intersection(set().union(*A))])

Output:

[[1, 5], [7], [6, 14], [17]]

For the more general case, one option is to create a dictionary and use the same idea as above in a loop:

lsts = [A,B,C]
d_unions = dict(enumerate([set().union(*X) for X in lsts]))
d_lsts = dict(enumerate(lsts))

out = []
for i, li in d_lsts.items():
    current_union = set.union(*[v for k,v in d_unions.items() if k!=i])
    out.extend([s_lst for s_lst in li if not set(s_lst).intersection(current_union)])

Output:

[[1, 5], [7], [100, 101]]

CodePudding user response:

You can try this one:

A = [[1,2,3],[1,5],[7],[8,9,10],[11]]
B = [[11,2,2],[9,11],[6,14], [17]]
C = [[17,18,19], [14,10],[100,101]]
lst=[A,B,C]
def non_common(ls):
    temp=[]
    for l in ls:
        without_l=[j for j in ls if j!=l] #get the list without the list-element we are iterating
        no_cmn=[i for i in l if (all(set(i).isdisjoint(set(j)) for k in without_l for j in k))]
        temp.extend(no_cmn)
    return temp
result=non_common(lst)
print(result)

You can also backtrack every list element to it's list by using enumerate(ls) in the loop.

  • Related