python下判断一个集合是否为另一个集合的子集的两种方法

文章概要:

1.判断集合子集的两种方法

2.python中集合set的issubset函数的源码实现

通常判断集合的子集一般都是使用issubset,但是今天在看到一段代码:判断一个权限列表是否为另一个权限列表的子集时看到用到了相减的方法,感觉很有意思,所以做个记录

x = {3, 4}
y = {3, 4, 5, 6}


if 0 == len(x - y):
    print "true"
else:
    print "False"

if x.issubset(y):
    print "true"
else:
    print "False"


输出:
true
true

issubset

x.issubset(y)判断集合x是否为集合y的子集

查看python2.7的源码

def issubset(self, other):
    """Report whether another set contains this set."""
    self._binary_sanity_check(other)
    if len(self) > len(other):  # Fast check for obvious cases
        return False
    for elt in ifilterfalse(other._data.__contains__, self):
        return False
    return True

以上面的x.issubset(y)进行说明:

self._binary_sanity_check判断y集合是否为set类型

ifilterfalse(other._data.__contains__, self)将x集合中不在y集合里的值过滤出来

所以,如果过滤出值说明集合y不能包含集合x,即x不是y的子集

这个other._data是个字典,利用字典的__contains__方法作为ifilterfalse函数的参数

可以看下ifilterfalse的作用及使用方法,这个接口在itertools包里

可以看下ifilterfalse函数的 源码实现

@six.add_metaclass(ABCMeta)
class BaseFilter(BaseItertool):
    def __init__(self, pred, seq):
        self._predicate = pred
        self._iter = iter_(seq)

    @abstractmethod
    def __next__(self):
        pass


class ifilter(BaseFilter):
    """ifilter(function or None, iterable) --> ifilter object
    Return an iterator yielding those items of iterable for which
    function(item) is true. If function is None, return the items that are
    true.
    """

    def _keep(self, value):
        predicate = bool if self._predicate is None else self._predicate
        return predicate(value)

    def __next__(self):
        val = next(self._iter)
        while not self._keep(val):
            val = next(self._iter)
        return val


class ifilterfalse(ifilter):
    """ifilterfalse(function or None, sequence) --> ifilterfalse object
    Return those items of sequence for which function(item) is false.
    If function is None, return the items that are false.
    """
    def _keep(self, value):
        return not super(ifilterfalse, self)._keep(value)

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值