作者:纽约纽约MrWaNg | 来源:互联网 | 2024-11-11 19:27
文章概要:1.判断集合子集的两种方法2.python中集合set的issubset函数的源码实现通常判断集合的子集一般都是使用issubset,但是今天在看到一段代码:判断一个权限列表是否为另一个权限
文章概要:
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)