Python: test empty set intersection without creati

2019-06-26 14:10发布

问题:

I often find myself wanting to test the intersection of two sets without using the result of the intersections.

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

The problem is that a new set is created to do this test which can be inefficient.

Is there a short way to do this without explicitly writing it out (as in the following)?

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

回答1:

You are looking for set.isdisjoint(), as sets are disjoint if and only if they have an empty intersection.

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


回答2:

You can use set.isdisjoint() to test wheather two sets have an empty intersection, just negate for the oposite:

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

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