Python: 在不创建新集的情况下测试空集交集

Python: test empty set intersection without creation of new set

我经常发现自己想要测试两个集合的交集而不使用交集的结果。

set1 = set([1,2])
set2 = set([2,3])
if(set1 & set2):
  print("Non-empty intersection")
else:
  print("Empty intersection")

问题是创建一个新集来执行此测试可能效率低下。

有没有一种不用明确写出来的捷径(如下所示)?

if(any(x in set2 for x in set1)):
  print("Non-empty intersection")
else:
  print("Empty intersection")

当且仅当它们有一个空交叉路口时,您正在寻找 set.isdisjoint(), as sets are disjoint

>>> set1 = set([1,2])
>>> set2 = set([2,3])
>>> set1.isdisjoint(set2)
False

可以用set.isdisjoint()来检验两个集合是否有空交集,相反的取反即可:

set1 = set([1,2])
set2 = set([2,3])

if not set1.sidisjoint(set2):
  print("Non-empty intersection")
else:
  print("Empty intersection")