Python: See if one set contains another entirely?

前端 未结 7 1701
长情又很酷
长情又很酷 2020-12-13 05:11

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

Something like:

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

>>>[1, 2,         


        
7条回答
  •  青春惊慌失措
    2020-12-13 06:03

    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
    

提交回复
热议问题