如何在 Python 中连接两个集合
Jinku Hu
2023年1月30日
Python
Python Set
-
在 Python 中通过
A |= B连接两个集合 -
在 Python 中通过
A.update(B)连接两个集合 -
在 Python 中通过
A.union(B)连接两个集合 -
在 Python 中通过
reduce(operator.or_, [A, B])连接两个集合
在本教程中,我们将介绍不同的方法来在 Python 中连接两个集合。
A |= BA.update(B)A.union(B)reduce(operator.or_, [A, B])
在 Python 中通过 A |= B 连接两个集合
A |= B 将集合 B 的所有元素添加到集合 A 中。
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A |= B
>>> A
{4, 5, 6, 7, 8, 9}
在 Python 中通过 A.update(B) 连接两个集合
A.update(B) 方法与 A |= B 相同。它就地修改集合 A 的内容。
>>> A = ["a", "b", "c"]
>>> B = ["b", "c", "d"]
>>> A.update(B)
>>> A
["a", "b", "c", "d"]
在 Python 中通过 A.union(B) 连接两个集合
A.union(B) 返回集合 A 和 B 的并集。它不会就地修改集合 A,而是会返回一个新集合。
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> A.union(B)
{1, 2, 3, 4, 5, 6}
>>> A
{1, 2, 3, 4}
此方法跟 A | B 相同。
在 Python 中通过 reduce(operator.or_, [A, B]) 连接两个集合
operator.or_(A, B) 返回 A 和 B 的按位或的结果,或 A 和 B 的并集,如果 A 和 B 是集合的话。
reduce 在 Python 2.x 中或 Python 2.x 和 3.x 中的 functools.reduce 都将函数应用于可迭代项。
因此,reduce(operator.or_, [A, B]) 将 or 函数应用于 A 和 B。它与 Python 表达式 A | B 相同。
>>> import operator
>>> from functools import reduce
>>> A = {4, 5, 6, 7}
>>> B = {6, 7, 8, 9}
>>> reduce(operator.or_, [A, B])
{4, 5, 6, 7, 8, 9}
注意
reduce 是 Python 2.x 的内置函数,但在 Python 3 中已弃用。
因此,我们需要使用 functools.reduce 来使代码在 Python 2 和 3 中兼容。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
