当前位置: 首页 > news >正文

python集合运算介绍及示例代码

Python 中的集合(set)是一种数据类型,用于存储唯一元素的无序集合。集合支持多种运算,如并集、交集、差集和对称差集,方便执行数学上的集合操作。

1. 创建集合

可以使用大括号 {} 或者 set() 函数创建集合:

# 使用大括号
set1 = {1, 2, 3, 4}
# 使用 set() 函数
set2 = set([3, 4, 5, 6])

2. 集合基本运算

2.1 并集 (union)

返回两个集合的并集,即包含两个集合中所有元素的集合。使用 | 操作符或者 union() 方法。

set1 = {1, 2, 3}
set2 = {3, 4, 5}# 并集
union_set = set1 | set2
# 或者
union_set = set1.union(set2)print(union_set)  # 输出: {1, 2, 3, 4, 5}
2.2 交集 (intersection)

返回两个集合的交集,即两个集合中都包含的元素。使用 & 操作符或者 intersection() 方法。

# 交集
intersection_set = set1 & set2
# 或者
intersection_set = set1.intersection(set2)print(intersection_set)  # 输出: {3}
2.3 差集 (difference)

返回只在第一个集合中而不在第二个集合中的元素。使用 - 操作符或者 difference() 方法。

# 差集
difference_set = set1 - set2
# 或者
difference_set = set1.difference(set2)print(difference_set)  # 输出: {1, 2}
2.4 对称差集 (symmetric_difference)

返回在两个集合中,但不同时存在于两个集合中的元素。使用 ^ 操作符或者 symmetric_difference() 方法。

# 对称差集
symmetric_difference_set = set1 ^ set2
# 或者
symmetric_difference_set = set1.symmetric_difference(set2)print(symmetric_difference_set)  # 输出: {1, 2, 4, 5}

3. 集合的其他常用方法

3.1 添加元素 (add)

使用 add() 方法向集合中添加元素。

set1.add(6)
print(set1)  # 输出: {1, 2, 3, 6}
3.2 删除元素 (remove 和 discard)

使用 remove() 方法删除集合中的指定元素,如果元素不存在会引发 KeyErrordiscard() 方法则不会引发错误。

set1.remove(6)
set1.discard(10)  # 不会报错
3.3 检查子集和超集
  • 使用 issubset() 方法检查一个集合是否是另一个集合的子集。
  • 使用 issuperset() 方法检查一个集合是否是另一个集合的超集。
set3 = {1, 2}
print(set3.issubset(set1))  # 输出: True
print(set1.issuperset(set3))  # 输出: True
3.4 清空集合 (clear)

使用 clear() 方法可以清空集合。

set1.clear()
print(set1)  # 输出: set()

集合运算适用于快速去重、元素关系判断等操作,是Python中功能强大的数据类型之一。

http://www.lryc.cn/news/444724.html

相关文章:

  • 『功能项目』按钮的打开关闭功能【73】
  • Linux 常用命令 - more 【分页显示文件内容】
  • Kotlin Android 环境搭建
  • 常见协议及其默认使用的端口号
  • 04-Docker常用命令
  • 数字化转型中的供应链管理优化
  • 【Python报错已解决】SyntaxError: invalid syntax
  • 树上差分+lca 黑暗的锁链
  • opencv4.5.5 GPU版本编译
  • 线性跟踪微分器TD详细测试(Simulink 算法框图+SCL完整源代码)
  • LabVIEW闪退
  • 【WPF】03 动态生成控件
  • 调试LTE模块碰到的4字节对齐问题
  • 一篇讲完HTML核心内容
  • 2024icpc(Ⅱ)网络赛补题 G
  • AIGC时代!AI的“iPhone时刻”与投资机遇
  • Kubernetes调度单位Pod
  • C语言指针篇
  • Unity 使用Editor工具查找 Prefab 中的指定脚本
  • Frida-JSAPI:Interceptor使用
  • 【深度学习】(3)--损失函数
  • git学习报告
  • Spring MVC的应用
  • JavaEE: 深入探索TCP网络编程的奇妙世界(六)
  • 探秘 Web Bluetooth API:连接蓝牙设备的新利器
  • Kubernetes Pod调度基础(kubernetes)
  • Angular由一个bug说起之十:npm Unsupported engine
  • Android 开发高频面试题之——Flutter
  • 视频单目标跟踪研究
  • 若依vue3.0表格的增删改查文件封装