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() 方法删除集合中的指定元素,如果元素不存在会引发 KeyError。discard() 方法则不会引发错误。

复制代码
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中功能强大的数据类型之一。

相关推荐
Ponp_6 小时前
用 StyleGAN2 做图像数据扩充实战
python·深度学习·生成对抗网络
郝学胜-神的一滴9 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove9 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
富贵儿9989 小时前
NL2SQL 实践手记 08:SQL 没报错,答案为什么不对——从失败复盘到 Workflow 修复
数据库·python·sql·ai·自然语言处理·langchain
代码民工正电荷10 小时前
JAVA学习基础(一)
java·开发语言·学习
无巧不成书021811 小时前
最新 PyPI可信发布完整教程 GitHub Actions+OIDC零Token实现Python包自动化发布
python·自动化·github·pypi
至为芯11 小时前
IP5387至为芯支持三路C口140W双向快充新国标移动电源方案芯片
c语言·开发语言·智能手机
星恒随风13 小时前
C++11 加餐(2)并发支持库——mutex、lock_guard、unique_lock 与死锁问题
开发语言·c++
东莞市云毅网络有限公司15 小时前
用 Node 做收录快照的周对比:差集、阈值与告警
python·sqlite·自动化运维·geo·数据监测