08 - 集合set:去重和快速查找

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass

仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

08 - 集合set:去重和快速查找

学习目标: 掌握集合的创建和应用


💻 代码示例

1. 创建集合

python 复制代码
# 方法1:花括号
s = {1, 2, 3, 4, 5}
print(s)  # {1, 2, 3, 4, 5}

# 方法2:set()函数
s = set([1, 2, 2, 3, 3, 3])  # 自动去重
print(s)  # {1, 2, 3}

# 空集合(⚠️ 不能用{},那是空字典)
empty = set()

# 从字符串创建
chars = set("hello")
print(chars)  # {'h', 'e', 'l', 'o'}

2. 集合操作

python 复制代码
s = {1, 2, 3}

# 添加元素
s.add(4)
print(s)  # {1, 2, 3, 4}

# 删除元素
s.remove(2)  # 如果元素不存在会报错
print(s)  # {1, 3, 4}

s.discard(10)  # 元素不存在也不报错

# 检查成员
print(1 in s)   # True
print(10 in s)  # False

# 长度
print(len(s))  # 3

3. 集合运算

python 复制代码
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))

# 差集
print(a - b)  # {1, 2}
print(a.difference(b))

# 对称差集
print(a ^ b)  # {1, 2, 5, 6}

🎯 在算法题中的应用

python 复制代码
# 第3课:最长连续序列
def longestConsecutive(nums):
    num_set = set(nums)  # O(1)查找
    longest = 0

    for num in num_set:
        # 只从序列起点开始
        if num - 1 not in num_set:
            current = num
            length = 1

            while current + 1 in num_set:
                current += 1
                length += 1

            longest = max(longest, length)

    return longest

# 去重
nums = [1, 2, 2, 3, 3, 3]
unique = list(set(nums))  # [1, 2, 3]

🎓 小结

{1, 2, 3} 创建集合

s.add(x) 添加元素

x in s O(1)查找

| & - ^ 集合运算

✅ 自动去重

核心优势: O(1)查找,类似字典但只存值不存键值对

下一步 : 09-字符串str.md


如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass

更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。

相关推荐
ZHW_AI课题组10 分钟前
使用DBSCAN算法对纽约市 Airbnb 房源数据集进行聚类分析
算法
蓦然回首却已人去楼空1 小时前
【分词:中文分词】BPE字节级分词算法实现汉字表达!
java·算法·中文分词
3DVisionary1 小时前
aero-engine-blade-thermal-fatigue-dic-inspection
人工智能·算法·机器学习·航空发动机·高温dic·涡轮叶片·热疲劳
Kurisu5751 小时前
深度拆解:从二进制切片到并发控制,大文件断点续传的底层工程设计
算法
梦想的颜色1 小时前
MySQL 数据存储结构与查询执行生命周期深度解析
运维·数据结构·数据库·mysql·线程·优化
Ameilide1 小时前
数据结构 算法解释,排序、查找
数据结构
随意起个昵称2 小时前
线性dp-LIS题目2(导弹拦截III)
算法·动态规划·图论
地平线开发者2 小时前
工具链使用从入门到顺手
算法
明航咨询—张老师2 小时前
AI工具狂飙时代:三款实用AI产品深度横向测评
大数据·人工智能·算法·it
真实的菜2 小时前
Redis 从入门到精通(二):深入数据结构 —— 从 RedisObject 到 SkipList 的源码级拆解
数据结构·redis·skiplist