温馨提示×

在Python中如何使用set方法求交集

小樊
86
2024-09-16 11:45:19
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用内置的集合(set)类型来求两个集合的交集。具体来说,可以使用 intersection 方法或者 & 运算符来实现这一目标。下面是两种方法的示例:

# 使用 intersection 方法
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set)  # 输出: {3, 4}

# 使用 & 运算符
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1 & set2
print(intersection_set)  # 输出: {3, 4}

在这两个示例中,我们首先定义了两个集合 set1set2,然后使用 intersection 方法或 & 运算符来求它们的交集。最后,我们打印出交集,得到结果 {3, 4}

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

推荐阅读:python set运算的交集如何求

0