Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersection of three sets in python?

Currently I am stuck trying to find the intersection of three sets. Now these sets are really lists that I am converting into sets, and then trying to find the intersection of.

Here's what I have so far:

for list1 in masterlist:
    list1 = thingList1
for list2 in masterlist:
    list2 = thingList2
for list3 in masterlist:
    list3 = thingList3

d3 = [set(thingList1), set(thingList2), set(thingList3)] 
setmatches c = set.intersection(*map(set,d3)) 
print setmatches

and I'm getting

set([]) 
Script terminated.

I know there's a much simpler and better way to do this, but I can't find one...

EDIT

Okay, here's what I have now.

setList=()
setList2=()
setList3=()

for list1 in masterlist:
    setList=list1
    for list2 in masterlist:
        setList2=list2
        for list3 in masterlist:
            setList3=list3



setmatches=set(setList) & set(setList2) & set(setList3)
print setmatches

Still doesn't give me what I'm looking for: which is the one match I ensured was in each list. It's giving me what looks like an addition of all the sets.

like image 310
thephfactor Avatar asked Oct 08 '12 21:10

thephfactor


People also ask

How do you find the intersection of three sets in Python?

Python Set intersection() Method The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.

How do you find the intersection of multiple sets in Python?

Use set. intersection() to find the intersection of multiple sets. Call set. intersection(*s) with any number of sets as *s to find their intersection.

How do you calculate intersection in Python?

We can use a method called intersection in python and set intersection operator, i.e. &, to get the intersection of two or more sets. The set intersection operator only works with sets, but the set intersection() method can be used with any iterable, like strings, lists, and dictionaries.


1 Answers

I think you are simply looking for:

set(thingList1) & set(thingList2) & set(thingList3)

The ampersand is intersection in Python (and some other languages as well).

like image 140
mjgpy3 Avatar answered Sep 28 '22 13:09

mjgpy3