假设S和T是指定的集合。不使用连接运算符|,我怎么能找到两个集合的并集?例如,这个可以找到交集:

S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }

不使用|如何找到一行中两个集合的并集?


当前回答

如果你愿意修改原始集合(在某些情况下你可能想这样做),你可以使用set.update():

S.update(T)

返回值为None,但S将被更新为原始S和T的并集。

其他回答

set.union(other_set)

注意,它返回一个新的集合,即它不修改自己。

假设你有两个列表

 A = [1,2,3,4]
 B = [3,4,5,6]

所以你可以找到A工会B,如下所示

 union = set(A).union(set(B))

如果你想找到交点和非交点,你可以这样做

 intersection = set(A).intersection(set(B))
 non_intersection = union - intersection

你可以使用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])

你可以像这样将这两个集合解压缩成一个:

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

*解包集合。解包是将可迭代对象(例如集合或列表)表示为它产生的每一项。这意味着上面的例子简化为{1,2,3,4,3,4,5,6},然后简化为{1,2,3,4,5,6},因为集合只能包含唯一的项。

如果你说的加入是指工会,试试这个:

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

这是一个有点hack,但我不能想到一个更好的内衬来做它。