Python: See if one set contains another entirely?

2019-03-09 05:50发布

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

Something like:

>>>[1, 2, 3].containsAll([2, 1])
True

>>>[1, 2, 3].containsAll([3, 5, 9])
False

标签: python set
7条回答
Rolldiameter
2楼-- · 2019-03-09 06:34
>>> set([1,2,3]).issuperset(set([2,1]))
True 
>>>    
>>> set([1,2,3]).issuperset(set([3,5,9]))
False
查看更多
聊天终结者
3楼-- · 2019-03-09 06:35

Below function return 0 if mainlist doesn't contains sublist fully and 1 if contains fully.

def islistsubset(sublist,mainlist):
     for item in sublist:
             if item in mainlist:
                     contains = 1
             else:
                     contains = 0
                     break;
     return contains
查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-09 06:36

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

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

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

>>> set([2, 1]) <= set([1, 2, 3])
True
>>> set([1, 2, 3]) >= set([2, 1])
True
查看更多
Viruses.
5楼-- · 2019-03-09 06:37

One option is left untouched -- subtraction:

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

Basically you check what elements in first list are not in second list.

I found it very handy since you could show what 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
查看更多
Summer. ? 凉城
6楼-- · 2019-03-09 06:46

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

>>> set([1,2,3]) >= set([2,1])
True
>>> set([1,2,3]) >= set([3,5,9])
False
查看更多
Explosion°爆炸
7楼-- · 2019-03-09 06:47

Those are lists, but if you really mean sets 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 will not be able to do better than checking each element.

查看更多
登录 后发表回答