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

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

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


当前回答

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

其他回答

假设您也不能使用s.u nunion (t),它等价于s.| t,您可以尝试一下

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

或者,如果你想要理解,

>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])

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

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

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

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