Brandon Charette
Brandon Charette

Reputation: 47

Trouble Comparing Elements of Sets (Python)?

I'm working on a program in which I need to check each element of a set (from a list of sets) and compare it against a 'master' set and then append the set to a list if at least a single element of the two sets match.

I tried attacking this problem like a list only to realize that indexing doesn't work on sets.

Ex of what I'm trying to accomplish:

newlist = []
i = set([5, 3, 1]) # <-- 'Master' Set
z = set([5, 0, 4])

#Output should be -> newlist = [set([5,0,4])]

Upvotes: 0

Views: 329

Answers (2)

timrau
timrau

Reputation: 23058

Assume z is list of sets like in your question description but not in your attached snippet.

newlist = [x for x in z if not i.isdisjoint(set(x))]
# or newlist = [x for x in z if i.intersection(set(x))]

Live demo

Upvotes: 1

Pipo
Pipo

Reputation: 101

You can use a combination of intersection and set to solve this problem:

>>> s1 = set([1,2,3])
>>> s2 = set([3,4,5])
>>> s3 = set([6,7,8])
>>> len(s1.intersection(s2))
1
>>> len(s1.intersection(s3))
0

So basically, write an if statement to check the length of the intersection of the two sets. If length is greater than 0, make newlist equal to your second set.

Upvotes: 0

Related Questions