Python set Union and set Intersection operate differently?

后端 未结 4 1613
无人及你
无人及你 2021-01-30 16:25

I\'m doing some set operations in Python, and I noticed something odd..

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


        
4条回答
  •  不要未来只要你来
    2021-01-30 17:15

    When you do set() you are creating an empty set. When you do set().intersection(...) you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.

    If you actually 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 can't do this directly with the way you're doing it, though, because you don't actually have any sets at all in your example with intersection(*...). You just have a list of lists. You should first convert the elements in your list to sets. So if you have

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

    you should do

    x = [set(a) for a in x]
    

提交回复
热议问题