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 删除元素 (removediscard)

使用 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中功能强大的数据类型之一。

相关推荐
数据智能老司机10 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机11 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i11 小时前
drf初步梳理
python·django
每日AI新事件11 小时前
python的异步函数
python
这里有鱼汤12 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试