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

1949idc 2年前 (2024-09-18) 阅读数 368 #编程语言

在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}

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业