在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}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:sql求两表的并集、交集、非交集、差集、结果集排序