conflicting cases in python lists

Viewed 164

I have two lists of sets -

attribute = [{0, 1, 2, 3, 6, 7}, {4, 5}]

and

decision = [{0, 1, 2}, {3, 4}, {5}, {6, 7}]

I want -

{3, 4}

Here, {3, 4} is conflicting, as it is neither a subset of {0, 1, 2, 3, 6, 7}, nor of {4, 5}.

My code -

 check = []
 for i in attribute:
      for j in decision:
          if j.issubset(i):
              check.append(j)
 print(check)

 for x in decision:
     if not x in check:
         temp = x

 print(temp)

This gives me {3, 4}, but is there any easier (and/ or) faster way to do this?

2 Answers

You can use the following list comprehension:

[d for d in decision if not any(d <= a for a in attribute)]

This returns:

[{3, 4}]

If you want just the first set that satisfies the criteria, you can use next with a generator expression instead:

next(d for d in decision if not any(d <= a for a in attribute))

This returns:

{3, 4}
result = [i for i in decision if not [j for j in attribute if i.issubset(j)]]

result is the list of all set they are not a subset of attribute. :)

This is the compact version of :

result = []
for i in decision:
    tmp_list = []
    for j in attribute:
        if i.issubset(j):
            tmp_list.append(j)
    if not tmp_list:
        result.append(i)
Related