Does Python set up a connection and set up an intersection to work differently?

I am doing some typing operations in Python, and I noticed something strange.

>> set([1,2,3]) | set([2,3,4]) set([1, 2, 3, 4]) >> set().union(*[[1,2,3], [2,3,4]]) set([1, 2, 3, 4]) 

This is a good, expected behavior - but with an intersection:

 >> set([1,2,3]) & set([2,3,4]) set([2, 3]) >> set().intersection(*[[1,2,3], [2,3,4]]) set([]) 

Am I losing my mind here? Why is the set.intersection () function not working as I expected?

How can I intersect a set of sets, as was the case with a union (if [[1,2,3], [2,3,4]] had a whole group of more lists)? What will be the "pythonic" way?

+45
python set union intersection
Oct. 25 '13 at 4:09
source share
4 answers

When you do set() , you create an empty set. When you do set().intersection(...) , you intersect this empty set with other things. The intersection of an empty set with any other set of sets is empty.

If you have a list of sets, you can get their intersection, similar to how you did it.

 >>> x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}] >>> set.intersection(*x) set([3]) 

You cannot do this directly with the way you do it, because you actually don't have any sets in your example using intersection(*...) . You have a list of listings. First you need to convert the items to your list into settings. Therefore, if you have

 x = [[1,2,3], [2,3,4]] 

you have to do

 x = [set(a) for a in x] 
+73
Oct 25 '13 at 4:12
source share
 set().intersection(*[[1,2,3], [2,3,4]]) 

of course it’s empty because you start with an empty set and intersect it with all the others

You can try calling the method on class

 set.intersection(*[[1,2,3], [2,3,4]]) 

but this will not work, because the first argument passed must be a set

 set.intersection({1, 2, 3}, *[[2,3,4], ...]) 

It looks awkward, better if you can use the list of sets in the first place. Especially if they come from a generator, which makes it difficult to clean the first element.

 set.intersection(*[{1,2,3}, {2,3,4}]) 

Otherwise, you can just do them all in sets

 set.intersection(*(set(x) for x in [[1,2,3], [2,3,4]])) 
+13
Oct 25 '13 at 4:23
source share

convert list to install first

 >>> set.intersection(*[set([1,2,3]), set([2,3,4])]) set([2, 3]) 

For several lists you can use,

 >>> set.intersection(*[set([1,2,3]), set([2,3,4]), set([5,3,4])]) set([3]) 
+8
Oct 25 '13 at 4:16
source share

[deleted incorrect answer]

Since @Anto Vinish suggested you first convert the lists for installation and then use set.intersect ion. For example:

 >>> sets = [set([1, 2, 3]), set([2, 3, 4]), set([3, 4, 5])] >>> set.intersection(*sets) set([3]) 
+1
Oct 25 '13 at 4:12
source share



All Articles