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

前端 未结 8 1045
闹比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: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.

提交回复
热议问题