13 - collections模块:高级数据结构

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

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

13 - collections模块:高级数据结构

学习目标: 掌握Counter, defaultdict, deque


💻 代码示例

1. Counter - 计数器

python 复制代码
from collections import Counter

# 统计元素出现次数
nums = [1, 2, 2, 3, 3, 3]
count = Counter(nums)
print(count)  # Counter({3: 3, 2: 2, 1: 1})

# 统计字符
s = "hello"
char_count = Counter(s)
print(char_count)  # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

# 访问计数
print(count[2])  # 2
print(count[10])  # 0 (不存在返回0,不报错)

# 最常见的元素
print(char_count.most_common(2))  # [('l', 2), ('h', 1)]

# Counter运算
c1 = Counter("hello")
c2 = Counter("world")
print(c1 + c2)  # 相加
print(c1 - c2)  # 相减

2. defaultdict - 默认值字典

python 复制代码
from collections import defaultdict

# 普通字典
d = {}
# d["key"].append(1)  # ❌ KeyError

# defaultdict自动创建默认值
d = defaultdict(list)  # 默认值是list
d["key"].append(1)
d["key"].append(2)
print(d)  # {'key': [1, 2]}

# 默认值是int(用于计数)
count = defaultdict(int)
for char in "hello":
    count[char] += 1  # 不存在的键默认为0
print(dict(count))  # {'h': 1, 'e': 1, 'l': 2, 'o': 1}

# 默认值是set
groups = defaultdict(set)
groups["A"].add(1)
groups["A"].add(2)
print(dict(groups))  # {'A': {1, 2}}

3. deque - 双端队列

python 复制代码
from collections import deque

# 创建队列
q = deque([1, 2, 3])

# 右端操作(O(1))
q.append(4)       # [1, 2, 3, 4]
print(q.pop())    # 4, 队列变成[1, 2, 3]

# 左端操作(O(1))
q.appendleft(0)   # [0, 1, 2, 3]
print(q.popleft())  # 0, 队列变成[1, 2, 3]

# 作为队列(FIFO)
queue = deque()
queue.append(1)  # 入队
queue.append(2)
print(queue.popleft())  # 1 出队

# 作为栈(LIFO)
stack = deque()
stack.append(1)  # 入栈
stack.append(2)
print(stack.pop())  # 2 出栈

# 限制长度
recent = deque(maxlen=3)
for i in range(5):
    recent.append(i)
print(recent)  # deque([2, 3, 4])

🎯 在算法题中的应用

python 复制代码
# Counter: 字母异位词
from collections import Counter

def isAnagram(s, t):
    return Counter(s) == Counter(t)

# defaultdict: 分组
from collections import defaultdict

def groupAnagrams(strs):
    groups = defaultdict(list)
    for word in strs:
        key = "".join(sorted(word))
        groups[key].append(word)
    return list(groups.values())

# deque: BFS层序遍历
from collections import deque

def levelOrder(root):
    if not root:
        return []

    result = []
    queue = deque([root])

    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        result.append(level)

    return result

# deque: 滑动窗口最大值(单调队列)
def maxSlidingWindow(nums, k):
    from collections import deque
    dq = deque()
    result = []

    for i, num in enumerate(nums):
        # 移除队首过期元素
        while dq and dq[0] < i - k + 1:
            dq.popleft()

        # 移除队尾小于当前元素的
        while dq and nums[dq[-1]] < num:
            dq.pop()

        dq.append(i)

        if i >= k - 1:
            result.append(nums[dq[0]])

    return result

🎓 小结

Counter : 统计元素出现次数

defaultdict : 自动创建默认值,避免KeyError

deque: 双端队列,两端操作都是O(1)

使用场景:

  • Counter: 计数、频率统计
  • defaultdict: 分组、建图
  • deque: BFS、滑动窗口、单调队列

下一步 : 14-heapq模块.md


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

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

相关推荐
Yzzz-F4 小时前
Problem - 2146D1 - Codeforces &&Problem - D2 - Codeforces
算法
Kk.08024 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
环黄金线HHJX.4 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互
Omics Pro4 小时前
虚拟细胞:开启HIV/AIDS治疗新纪元的关键?
大数据·数据库·人工智能·深度学习·算法·机器学习·计算机视觉
旖-旎5 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择
_日拱一卒5 小时前
LeetCode:合并区间
算法·leetcode·职场和发展
xiaoye-duck5 小时前
【C++:哈希表封装】哈希表封装 myunordered_map/myunordered_set 实战:底层原理 + 完整实现
数据结构·c++·散列表
汀、人工智能5 小时前
[特殊字符] 第3课:最长连续序列
数据结构·算法·数据库架构·图论·bfs·最长连续序列
少许极端5 小时前
算法奇妙屋(四十一)-贪心算法学习之路 8
学习·算法·贪心算法
Kethy__5 小时前
计算机中级-数据库系统工程师-数据结构-图
数据结构·算法·软考··数据库系统工程师·计算机中级