What Problems Are Python Sets Best At Solving?



☰

开始北极星测评

Python 学习笔记

What Problems Are Python Sets Best At Solving?

Learn when to use a set for deduplication, fast membership checks, and set operations, and when a list or dict is the better tool.

Python 学习笔记

集合到底擅长解决什么问题?

讲清 set 在去重、快速查询和集合运算中的优势,以及何时应该改用 list 或 dict。

分享这篇文章

复制链接、使用手机分享、用微信扫码,或通过邮件发送。




邮箱

The list is Python's most-used container, so many students reach for it even when the task is "check whether something is there" or "remove the duplicates": a loop with in, plus a second list for dedup. Small data hides the cost; in contest problems, one O(N²) lookup turns an accepted solution into a timeout — the kind that surfaces seconds before the deadline. This note spells out the three jobs sets are genuinely good at — deduplication, fast membership, and set operations — where they fall short, and how sets and dicts divide the work.

The Common Mistake

names = ["amy", "bob", "amy", "cid", "bob"]
unique = []
for name in names:
    if name not in unique:      # scans unique from scratch every time
        unique.append(name)
print(unique)

name not in unique compares against the whole list element by element: deduplicating N items costs 1+2+…+N comparisons, N² in the worst case. A thousand items means about half a million comparisons; a hundred thousand grinds to a halt. Worse, samples often have only a few dozen items, so it runs fine locally and times out on the judge — the bill arrives at the most expensive moment.

The Core Idea

A set is an unordered container of unique values (the 01020 lesson's definition). Unpack that sentence and you get its three weapons:

  1. Deduplication is built in: throw any sequence into set() and duplicates vanish, O(N).
  2. Membership is O(1): x in s uses hashing, independent of size; a list scans in O(N). In a maze you ask "have I been here?" at every step; set lookups keep the total linear.
  3. Set algebra is built in: union |, intersection &, difference - express "both like", "only in A" relationships in one line.

Watch a three-step trace: walking a grid with visited = set(); at cell (2,3), check (2,3) in visited — False, step in, add it; later, back at (2,3), check again — True, skip, no infinite loop. Every check is constant time no matter how many cells exist.

And remember the boundaries: a set keeps no order (do not use it when order matters) and holds only immutable elements (no lists or dicts inside; tuples are fine).

Sets vs Dicts: For Counting, Use a Dict

These two hash containers confuse every beginner. The difference is one sentence: a set answers only "is it there?"; a dict also answers "how many?".

votes = ["amy", "bob", "amy", "amy", "bob", "dan"]

who = set(votes)                 # who voted at all
count = {}
for name in votes:
    count[name] = count.get(name, 0) + 1

print(who)        # {'amy', 'bob', 'dan'}
print(count)      # {'amy': 3, 'bob': 2, 'dan': 1}

Whenever the question says "how many of each", "which rank", or "occurrence counts", the answer is a dict; only "is it there" or "is it new" belongs to a set. The two mistakes are symmetric: counting with a set loses the counts, and membership with a dict drags along a value you never read.

The Recommended Way

names = ["amy", "bob", "amy", "cid", "bob"]

unique = list(set(names))
print(unique)

a = {"amy", "bob"}
b = {"bob", "dan"}
print(a & b)    # intersection
print(a | b)    # union
print(a - b)    # difference
['amy', 'bob', 'cid']        # set element order is not guaranteed
{'bob'}
{'amy', 'bob', 'dan'}        # same
{'amy'}

One line per job: dedupe with set(names), query with x in s, combine with & | -. Note that a set's printed order is not guaranteed — compare sets by equality, not by eyeballing order.

Side by Side

Need Recommended Avoid Why
Deduplicate set list loop + in O(N) vs O(N²)
Fast membership set list hash O(1) vs scan O(N)
Count occurrences dict set a set forgets counts
Keep original order list set sets are unordered
Store lists/dicts as elements impossible; use tuples — sets accept immutables only

One line for choosing: "is it there?" → set; "how many?" → dict; "at which position?" → list.

In Real Problems

This exact choice recurs in contests. Walking a maze, record visited cells in a set: one lookup and one add per move, both constant time, no matter how long the path — the visited sets in the CCC 2026 J4 Snail Path walkthrough and the CCC 2020 J5/S2 Escape Room walkthrough are exactly this. Grouping people and answering "which group is this person in" uses a dict for name → group id plus a set for the checks — the core structure of the CCC 2022 J4/S2 Good Groups walkthrough (in production review).

Practice

  1. Turn scores = [70, 85, 70, 90, 85] into a deduped list in one line (hint: set ignores order — if order must survive, think of another way).
  2. With two course rosters math = {...} and cs = {...}, write one line listing students taking both.
  3. Challenge: why does {{1, 2}, {3, 4}} raise an error, and how would you store a collection of sets?

One Line to Remember

Dedup, membership, intersection/union/difference — those three jobs go to sets; for order, counting, or nesting, return to lists and dicts.

list 是 Python 里最常用的容器,于是很多同学遇到"查一查有没有""去掉重复的"也用 list 硬写:循环加 in,再写一个新列表去重。数据量小的时候看不出差别;到了竞赛题里,一个 O(N²) 的查找就能让程序从通过变成超时——而且是提交前最后几秒才暴露的那种超时。这篇讲清楚 set(集合)真正擅长的三件事——去重、快速查询、集合运算——以及它不适合什么、和 dict 怎么分工。

常见错误

names = ["amy", "bob", "amy", "cid", "bob"]
unique = []
for name in names:
    if name not in unique:      # 每次都把 unique 从头扫一遍
        unique.append(name)
print(unique)

name not in unique 对列表是逐个比较:N 个元素去重,最坏比较次数是 1+2+…+N,N² 级别。一千个元素要比较约五十万次,十万次量级就彻底卡死。更隐蔽的是,样例数据往往只有几十条,本地跑得好好的,评测机一上大数据就超时——错误的代价被延迟到最贵的时候才支付。

核心概念

集合是"无序、不重复"的容器(课程 01020 的定义)。这句话拆开就是它的三件武器:

  1. 去重是天然的:把任意序列扔进 set(),重复元素自动只留一份,O(N)。
  2. 查询是 O(1) 的:x in s 用哈希定位,和数据量无关;列表是 O(N) 逐个比。迷宫里"这格来过吗"这种问题,每走一步查一次,集合查询让总代价保持线性。
  3. 集合运算是内置的:并 |、交 &、差 -,一行写出"两人共同喜欢的""只在 A 不在 B 的"这类关系。

看一个三步的小轨迹:走格子,visited = set();走到 (2,3),先查 (2,3) in visited——False,走进去,加进集合;绕回 (2,3) 再查——True,直接跳过,不会死循环。整个判断是常数时间,和已经走过多少格无关。

反过来也要记住边界:集合不保证顺序(需要顺序就别用它),只能装不可变元素(列表、字典进不了集合,元组可以)。

set 和 dict 的分工:要计数就别用 set

这两样都是哈希容器,新手最常混。区别只有一句:set 只回答"在不在",dict 还能回答"有几个"。

votes = ["amy", "bob", "amy", "amy", "bob", "dan"]

who = set(votes)                 # 谁投过票
count = {}
for name in votes:
    count[name] = count.get(name, 0) + 1

print(who)        # {'amy', 'bob', 'dan'}
print(count)      # {'amy': 3, 'bob': 2, 'dan': 1}

只要问题里出现"各有多少""第几名""出现次数",答案就是 dict;只是"有没有""是不是新东西",才是 set。选错的代价很对称:用 set 计数会丢掉次数信息,用 dict 查成员则要多维护一层没必要的值。

推荐写法

names = ["amy", "bob", "amy", "cid", "bob"]

unique = list(set(names))
print(unique)

a = {"amy", "bob"}
b = {"bob", "dan"}
print(a & b)    # 交集
print(a | b)    # 并集
print(a - b)    # 差集
['amy', 'bob', 'cid']        # 集合元素的顺序可能不同
{'bob'}
{'amy', 'bob', 'dan'}        # 同上
{'amy'}

三件事各一行:去重 set(names)、查询 x in s、运算 & | -。注意输出里集合元素的先后顺序是不保证的,比较结果请用相等判断而不是肉眼看顺序。

对比一下

需求 推荐 不推荐 为什么
去重 set list 循环 + in O(N) vs O(N²)
快速查成员 set list 哈希 O(1) vs 逐个 O(N)
计数(每个出现几次) dict set set 不记次数
保持原顺序 list set set 无序
装列表/字典当元素 不行,改用 tuple — 集合只收不可变元素

一句话选型:只关心"有没有"用 set,关心"有几个"用 dict,关心"排第几"用 list。

用到真题里

这套选型在竞赛题里反复出现。走迷宫时记录"到过的格子"用 set:每移动一步查一次、加一次,都是常数时间,路径再长也不会拖慢判断——CCC 2026 J4 Snail Path 题解和 CCC 2020 J5/S2 Escape Room 题解里的 visited 集合就是这个选择。要按内容分组、查"这个人属于哪组"时,dict 做"名字 → 组号"的映射,配上一组集合做判定,就是 CCC 2022 J4/S2 Good Groups 题解(production 复核中)的核心结构。

小练习

  1. 用一行把 scores = [70, 85, 70, 90, 85] 变成去重后的列表(提示:set 不管顺序,如果必须保持原顺序,想想还有什么办法)。
  2. 有两组选课学生 math = {...}、cs = {...},写一行找出"两门都选"的学生。
  3. 挑战:为什么 {{1, 2}, {3, 4}} 会报错?要装"集合的集合"该怎么改?

一句话记住

去重、查有没有、算交集并集差集——这三件事找 set;要顺序、要计数、要嵌套,就回到 list 和 dict。

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to Python Learning Notes
返回Python 学习笔记

滚动至顶部