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):
false是什么函数"""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)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。