intersection of three sets in python?

六月ゝ 毕业季﹏ 提交于 2021-02-07 08:19:19

问题


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.


回答1:


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).




回答2:


set1 & set2 & set3

should work ... at least I think

>>> set((1,2,3)) & set((2,3,4)) & set((3,4,5))
set([3])



回答3:


set.intersection(*map(set,d3)) 

Will actually work, though because d3 already contains sets you can just do:

set.intersection(*d3)

And, in fact, only the first one needs to be a set - the others can be any iterable, and intersection will setify them by itself.

The problem you're having doesn't seem to be in this code - rather,

for list1 in masterlist:
    list1 = thingList1

Won't actually put anything into thingList1. It is hard to tell without seeing what masterlist looks like, but you may want something like:

for list1 in masterlist:
   thingList1[:] = list1

print your three lists before you do the intersection to make sure they contain what you expect.




回答4:


A list of sets, you say?

In [1]: mylist = [ [1, 2, 3, 4], [3, 4, 5, 6, 7], [2, 3, 4, 5, 6] ]

In [2]: result = set(mylist[0])

In [3]: for item in mylist:
   ...:     result = result.intersection(item)
   ...:     
   ...:     

In [4]: result
Out[4]: set([3, 4])



回答5:


You need something like this:

frozenset(list1) & frozenset(list2) & frozenset(list1)



回答6:


This should do the trick:

reduce(lambda x,y: x&y, mysetlist)


来源:https://stackoverflow.com/questions/12789820/intersection-of-three-sets-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!