Python:看看一个集合是否完全包含另一个集合?
有没有一种快速方法来检查一组是否完全包含另一组?
像这样的东西:
>>> set([1, 2, 3]).containsAll([2, 1])
True
>>> set([1, 2, 3]).containsAll([3, 5, 9])
False
Is there a fast way to check if one set entirely contains another?
Something like:
>>> set([1, 2, 3]).containsAll([2, 1])
True
>>> set([1, 2, 3]).containsAll([3, 5, 9])
False
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
set.issubset()
< /a> 或set.issuperset()
< /a> (或其基于运算符的对应项:<=
和>=
)。请注意,这些方法将接受任何可迭代作为参数,而不仅仅是集合:但是,如果您使用运算符,则两个参数都必须是集合:
You can use either
set.issubset()
orset.issuperset()
(or their operator based counterparts:<=
and>=
). Note that the methods will accept any iterable as an argument, not just a set:However, if you use operators, both arguments must be sets:
如果您怀疑一个集合是另一个集合的子集,并将这两个集合相交,则如果它是子集,则结果等于其自身。
If you suspect a set to be a subset of another, and intersect those two sets together, the result is equal to itself if it is a subset.
一个选项保持不变 - 减法:
基本上,您检查第一个列表中的哪些元素不在第二个列表中。
我发现它非常方便,因为您可以显示缺少哪些值:
One option is left untouched -- subtraction:
Basically, you check what elements in the first list are not in the second.
I found it very handy since you could show what values are missing:
如果主列表不完全包含子列表,下面的函数返回 0;如果完全包含,则返回 1。
Below function return 0 if mainlist doesn't contains sublist fully and 1 if contains fully.
这些是列表,但如果您真的指的是集合,您可以使用
issubset
方法。对于列表,您将无法比检查每个元素更好。
Those are lists, but if you really mean sets you can use the
issubset
method.For a list, you will not be able to do better than checking each element.
为了完整起见:这相当于
issubset
(尽管可以说有点不太明确/可读):For completeness: this is equivalent to
issubset
(although arguably a bit less explicit/readable):