Python: see if one set contains another completely?

Is there a quick way to check if one set contains another another?

Something like:

>>>[1, 2, 3].containsAll([2, 1]) True >>>[1, 2, 3].containsAll([3, 5, 9]) False 
+67
python set
May 4 '10 at 1:55 a.m.
source share
7 answers

These are lists, but if you really mean a lot, you can use the issubset method.

 >>> s = set([1,2,3]) >>> t = set([1,2]) >>> t.issubset(s) True >>> s.issuperset(t) True 

For a list, you cannot do better than checking each item.

+106
May 04 '10 at 13:57
source share

For completeness: this is equivalent to issubset (although perhaps the bit is less explicit / readable):

 >>> set([1,2,3]) >= set([2,1]) True >>> set([1,2,3]) >= set([3,5,9]) False 
+30
May 04 '10 at 2:06 a.m.
source share

One parameter is left untouched - subtraction:

 >>> {1, 2} - {1, 2, 3} set([]) >>> {1, 2, 3} - {1, 2} set([3]) 

Basically you check which items in the first list are not in the second list.

It was very convenient for me, since you could show which values ​​are missing:

 >>> def check_contains(a, b): ... diff = a - b ... if not diff: ... # All elements from a are present in b ... return True ... print('Some elements are missing: {}'.format(diff)) ... return False ... >>> check_contains({1, 2}, {1, 2, 3}) True >>> check_contains({1, 2, 3}, {1, 2}) Some elements are missing: set([3]) False 
+4
Apr 13 '16 at 12:42 on
source share

If you suspect that a set is a subset of the other, and intersect the two sets together, the result is equal to itself if it is a subset.

 a = [2,1,3,3] b = [5,4,3,2,1] set(a).intersection(set(b)) == set(a) >>True 
+3
Jun 06 '16 at 16:11
source share

You can use set.issubset() or set.issuperset() (or their operator counterparts: <= and >= ). Note that methods will take any iterable as an argument, not just a collection:

 >>> {1, 2}.issubset([1, 2, 3]) True >>> {1, 2, 3}.issuperset([1, 2]) True 

However, if you use operators, both arguments must be set:

 >>> {1, 2} <= {1, 2, 3} True >>> {1, 2, 3} >= {1, 2} True 
+1
Feb 13 '19 at 15:52
source share

Below the function returns 0 if the main list does not contain subscriptions completely and 1 if it contains completely.

 def islistsubset(sublist,mainlist): for item in sublist: if item in mainlist: contains = 1 else: contains = 0 break; return contains 
0
Oct 25 '17 at 12:05
source share
 >>> set([1,2,3]).issuperset(set([2,1])) True >>> >>> set([1,2,3]).issuperset(set([3,5,9])) False 
0
Jan 26 '18 at 8:47
source share



All Articles