python

set类型在Python中的交集、并集、差集如何计算

小樊
93
2024-09-06 13:06:29
栏目: 编程语言

在Python中,可以使用内置的set类型来计算两个集合的交集、并集和差集。这里是一些例子:

# 定义两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# 计算交集
intersection = set1.intersection(set2)
print("Intersection:", intersection)  # 输出:{4, 5}

# 计算并集
union = set1.union(set2)
print("Union:", union)  # 输出:{1, 2, 3, 4, 5, 6, 7, 8}

# 计算差集
difference = set1.difference(set2)
print("Difference:", difference)  # 输出:{1, 2, 3}

你还可以使用其他方法,比如 & 运算符计算交集,| 运算符计算并集,- 运算符计算差集:

# 计算交集
intersection = set1 & set2
print("Intersection:", intersection)  # 输出:{4, 5}

# 计算并集
union = set1 | set2
print("Union:", union)  # 输出:{1, 2, 3, 4, 5, 6, 7, 8}

# 计算差集
difference = set1 - set2
print("Difference:", difference)  # 输出:{1, 2, 3}

0
看了该问题的人还看了