python set运算的交集如何求

401
2024/8/27 12:31:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中可以使用set数据类型来表示集合,并通过内置方法intersection或&操作符来求两个集合的交集。

例如:

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

# 使用intersection方法求交集
intersection_set = set1.intersection(set2)
print("使用intersection方法求得的交集为:", intersection_set)

# 使用&操作符求交集
intersection_set = set1 & set2
print("使用&操作符求得的交集为:", intersection_set)

输出结果为:

使用intersection方法求得的交集为: {3, 4}
使用&操作符求得的交集为: {3, 4}

在这个例子中,我们首先定义了两个集合set1和set2,然后分别使用intersection方法和&操作符求得了它们的交集。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么创建一维数组