苦练Python第24天:玩转Set
前言
大家好,我是倔强青铜三。是一名热情的软件工程师,我热衷于分享和传播IT技术,致力于通过我的知识和技能推动技术交流与创新,欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到《100天Python》第24天!今天我们来解锁一种独特且强大的数据结构:Set(集合)。当你需要去重、快速成员检测或执行并集、交集、差集等数学运算时,Set 就是你的瑞士军刀。让我们开始吧!🐍
📦 今日收获清单
- 什么是 Set 及其创建方式
- Set 与 list、tuple 的异同
- 常用 Set 方法
- 四大集合运算:并、交、差、对称差
- 真实场景示例
🔹 1. Set 是什么?
Set 是一个无序、可变且无索引的集合,不允许重复元素。
🔹 语法
my_set = {1, 2, 3}
空集合必须用 set():
empty_set = set()
⚠️
{}创建的是空字典,不是空集合!
✅ 2. 为什么用 Set?
- 自动去重
- 成员测试超快(
in) - 数学运算一步到位
- 轻松比较两组数据
🔧 3. 基础操作
创建与添加
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
删除元素
fruits.remove("banana") # 不存在时报错
fruits.discard("banana") # 不存在不报错
清空与复制
fruits.clear()
new_set = fruits.copy()
🔁 4. 遍历 Set
for fruit in fruits:
print(fruit)
注意:Set 无序,输出顺序不一定与插入一致。
🔀 5. 四大集合运算
假设:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
🔸 并集 — 所有唯一元素
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b)) # 同上
🔸 交集 — 公共元素
print(a & b) # {3, 4}
print(a.intersection(b))
🔸 差集 — 只在 a 中的元素
print(a - b) # {1, 2}
print(a.difference(b))
🔸 对称差集 — 只在一边的元素
print(a ^ b) # {1, 2, 5, 6}
print(a.symmetric_difference(b))
🔎 6. 成员测试
print(3 in a) # True
print(10 in a) # False
在 Set 中比 list 快得多!
⚠️ 7. Set 与其他集合对比
| 特性 | list | tuple | set |
|---|---|---|---|
| 有序 | ✅ | ✅ | ❌ |
| 可变 | ✅ | ❌ | ✅ |
| 允许重复 | ✅ | ✅ | ❌ |
| 支持索引 | ✅ | ✅ | ❌ |
| 快速成员检测 | ❌ | ❌ | ✅ |
🧪 实战示例
1. 列表去重
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print(unique_nums) # [1, 2, 3, 4, 5]
2. 共同爱好检测
alice = {"reading", "coding", "travel"}
bob = {"coding", "gaming"}
print(alice & bob) # {'coding'}
3. 句子唯一词统计
sentence = "this is a test this is only a test"
unique_words = set(sentence.split())
print(unique_words)
🧠 今日速记
- Set = 无序 + 可变 + 去重
- 创建:
{1, 2, 3}或set() - 四大运算:
|、&、-、^ - 成员检测
in速度飞快 - 场景:去重、交集、关键词统计
最后感谢阅读!欢迎关注我,微信公众号:
倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!