Skip to content

Python 设置

Unordered 集合的 唯一元素: 设置操作, frozenset, and deduplication.

你将学到

  • 创建设置 and 添加/移除元素
  • 执行 union, intersection, and difference
  • Use 设置 for deduplication and membership 测试
  • 理解 frozenset for 不可变设置
  • 选择设置 over 列表 for 正确 use 情况

概念讲解

Creating Sets

set 是一种 unordered collection of unique elements. Duplicates are automatically removed:

empty = set()           # NOT {} — that creates a dict!
fruits = {"apple", "banana", "cherry"}
from_list = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

The most common way to create a set from existing data is 设置(iterable), which deduplicates automatically. Note that {} creates an empty dict, not an empty set — use 设置() for an empty set.

Adding and Removing

tags = {"python", "code"}

tags.add("学习")           # add one element
tags.update(["fun", "快"]) # add multiple
tags.discard("code")        # remove if present (no error if missing)
tags.remove("python")       # remove — KeyError if missing
tags.pop()                  # remove and return an arbitrary element

Use .discard() when the element might not exist — it does not raise an error. .移除() raises KeyError if the element is absent.

Set Operations

Sets support mathematical operations using operators or methods:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union — elements in either
print(a | b)         # {1, 2, 3, 4, 5, 6}
print(a.union(b))    # same thing

# Intersection — elements in both
print(a & b)                # {3, 4}
print(a.intersection(b))    # same

# Difference — elements in a but not b
print(a - b)             # {1, 2}
print(a.difference(b))   # same

# Symmetric difference — elements in exactly one
print(a ^ b)                     # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # same

# Subset and superset
print({1, 2}.issubset(a))   # True
print(a.issuperset({1, 2})) # True

The operator forms (| & - ^) are concise and readable. The method forms accept any iterable, not just sets.

Deduplication

The most common practical use of sets is removing duplicates from a list:

numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(numbers))  # [1, 2, 3, 4] (order not guaranteed)

Note: sets are unordered, so the order of the result is not guaranteed. If you need to preserve order while deduplicating, use dict.fromkeys() in Python 3.7+:

unique_ordered = list(dict.fromkeys(numbers))

Fast Membership Testing

Checking x in my_set is O(1) on average, while x in my_list is O(n). For large collections where you only test membership, a set is dramatically faster:

valid_ids = set(range(1_000_000))
print(500000 in valid_ids)  # instant — O(1)

frozenset

A frozenset is an immutable set — it cannot be modified after creation. Because it is hashable, it can be used as a dictionary key or an element of another set:

fs = frozenset([1, 2, 3])
# fs.add(4)  # AttributeError — immutable
d = {fs: "my frozen 设置"}  # valid — frozenset is hashable

When to Use Sets

  • Deduplication — remove duplicates from any iterable
  • Membership testing — fast in checks on large collections
  • Mathematical operations — union, intersection, difference
  • Removing items — when order does not matter and duplicates are unwanted

示例代码

              # Creating sets — duplicates removed automatically
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # {'apple', 'banana', 'cherry'}

from_list = set([1, 2, 2, 3, 3, 3])
print(from_list)  # {1, 2, 3}

# Adding and removing
tags = {"python", "code"}
tags.add("learn")
tags.update(["fun", "fast"])
tags.discard("missing")  # no error even if absent
print(tags)

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)  # union: {1, 2, 3, 4, 5, 6}
print(a & b)  # intersection: {3, 4}
print(a - b)  # difference: {1, 2}
print(a ^ b)  # symmetric diff: {1, 2, 5, 6}

# Deduplication
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(unique)

# Order-preserving deduplication
unique_ordered = list(dict.fromkeys(numbers))
print(unique_ordered)  # [1, 2, 3, 4]

# Fast membership test
valid = set(range(1000))
print(500 in valid)  # True — O(1) lookup

# frozenset — immutable, hashable
fs = frozenset([1, 2, 3])
d = {fs: "frozen"}
print(d[fs])
            

Demonstrates 设置 creation 使用 automatic deduplication, 添加/更新/discard, 所有 four 设置操作 (union, intersection, difference, symmetric difference), deduplication 使用 and 不使用顺序 preservation, 快 membership 测试, and frozenset as dict 键.

动手试一试

常见错误

错误写法

Using {} 到创建空 设置

正确做法

{} 创建空 dict, 不空 设置. Use 设置() 到创建空 设置. 这个是 very 常见初学者 mistake — 总是 use 设置() for 空设置.

错误写法

Expecting 设置到 preserve insertion 顺序

正确做法

设置是 unordered — iterating over 设置做 不 guarantee 任何 particular 顺序. 如果你 需要顺序 plus uniqueness, use dict.fromkeys() (Python 3.7+) or 列表使用 manual deduplication.

相关速查表

练习 Python 设置

3 个练习

练习 Python 设置

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误