How to join two sets in one line without using “|”

前端 未结 8 1042
闹比i
闹比i 2020-12-23 00:21

Assume that S and T are assigned sets. Without using the join operator |, how can I find the union of the two sets? This, for example,

相关标签:
8条回答
  • 2020-12-23 00:39

    If by join you mean union, try this:

    set(list(s) + list(t))
    

    It's a bit of a hack, but I can't think of a better one liner to do it.

    0 讨论(0)
  • 2020-12-23 00:41

    You could use or_ alias:

    >>> from operator import or_
    >>> from functools import reduce # python3 required
    >>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
    set([1, 2, 3, 4, 5, 6])
    
    0 讨论(0)
  • 2020-12-23 00:46

    Assuming you also can't use s.union(t), which is equivalent to s | t, you could try

    >>> from itertools import chain
    >>> set(chain(s,t))
    set([1, 2, 3, 4, 5, 6])
    

    Or, if you want a comprehension,

    >>> {i for j in (s,t) for i in j}
    set([1, 2, 3, 4, 5, 6])
    
    0 讨论(0)
  • 2020-12-23 00:48

    If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update():

    S.update(T)
    

    The return value is None, but S will be updated to be the union of the original S and T.

    0 讨论(0)
  • 2020-12-23 00:49

    You can just unpack both sets into one like this:

    >>> set_1 = {1, 2, 3, 4}
    >>> set_2 = {3, 4, 5, 6}
    >>> union = {*set_1, *set_2}
    >>> union
    {1, 2, 3, 4, 5, 6}
    

    The * unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6} which then simplifies to {1, 2, 3, 4, 5, 6} because the set can only contain unique items.

    0 讨论(0)
  • 2020-12-23 00:51

    You can do union or simple list comprehension

    [A.add(_) for _ in B]
    

    A would have all the elements of B

    0 讨论(0)
提交回复
热议问题