如何检查多个集合是否相交?

How to check whether many sets intersect?

我有很多集合,想知道它们是否有交集。目前使用以下代码:

if reduce(set.intersection, mysets):
    ...

有更好的方法吗?我不知何故听说 reduce 不好用。不过好像挺符合这个场景的。

恕我直言 reduce 完全可以使用(您可能想使用 functools.reduce 进入 Python3)。应该命令集合尽可能快地缩小(即,如果可能,首先拥有大部分不相交的集合)但这可能需要你可能不具备的先验知识。

但是,如果您使用的是 Python2.6 之后的版本,this question 的答案指出您可以使用 set.intersection。然后,您可以使用 set.intersection(*mysets).

来调用它

那么答案是:

2.6 之前的版本:使用 reduce

Post-2.6: 使用set.intersection