Coniper.top代码笔记

代码笔记 / Python

15、集合(set)

官方文档:https://docs.python.org/zh-cn/3.14/library/stdtypes.html#set-types-set-frozenset

一、集合是什么

在 Python 中,集合(set) 是一种特殊的数据类型,用来存储不重复的元素。

你可以把集合理解为:

“一堆不重复的东西放在一个无序的袋子里。”

有同学会问:既然有了列表、元组这些数据容器,py为什么还提供集合这样的数据类型呢?

在项目中,我们可能有这样的需求:

需要记录一些数据,而这些数据必须保证是不重复的,而且数据的顺序并没有要求,就可以考虑使用集合。

举例说明

fruits = {"apple", "banana", "orange", "apple"}
print(fruits)

运行结果:

{'banana', 'apple', 'orange'}

👉 集合自动去掉重复元素,所以只保留一个 "apple"。


二、集合的三大特点

特性

说明

示例

无序(unordered)

集合中元素没有固定顺序

输出顺序可能和定义顺序不同

不重复(unique)

相同的元素只会出现一次

{"a", "b", "a"} → {"a", "b"}

元素不可变(immutable)

集合中的元素必须是不可变类型(如数字、字符串、元组)

不能放列表、字典


三、创建集合的两种方式

1. 用大括号 {} 定义

set1 = {1, 2, 3}
print(set1)

2. 用 set() 函数把其他序列转成集合

set2 = set([1, 2, 2, 3, 4])
print(set2)     # {1, 2, 3, 4}  自动去重

⚠️ 注意:
创建空集合时必须写成 set(),
因为 {} 会被当成一个空字典。

a = {}          # 这是字典
b = set()       # 这是空集合

四、集合的基本操作

1. 添加元素

fruits = {"apple", "banana"}
fruits.add("orange")         # 添加一个元素
print(fruits)

结果:

{'banana', 'apple', 'orange'}

2. 删除元素

fruits.remove("banana")      # 删除指定元素(不存在会报错)
print(fruits)
fruits.discard("grape")      # 删除元素(不存在不会报错)

3. 随机删除一个元素

fruits.pop()

集合是无序的,因此 pop() 删除哪个元素不确定。

4. 清空集合

fruits.clear()
print(fruits)    # 输出 set()

五、集合的遍历

集合虽然无序(没有下标 故不能使用while),但可以使用 for 循环遍历:

colors = {"red", "green", "blue"}
for c in colors:
    print(c)

结果(顺序可能不同):

red
blue
green

六、集合的数学运算(非常重要!)

Python 的集合可以做各种数学集合运算,非常直观。

1. 交集(intersection)&

取两个集合共有的元素。

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A & B)

结果:

{3, 4}

2. 并集(union)|

把两个集合的所有元素合并起来(自动去重)。

print(A | B)

结果:

{1, 2, 3, 4, 5, 6}

3. 差集(difference)-

取只属于 A 而不属于 B 的元素。

print(A - B)

结果:

{1, 2}

4. 对称差集(symmetric difference)^

取只在 A 或只在 B 中存在的元素。

print(A ^ B)

结果:

{1, 2, 5, 6}

📘 等价函数写法

运算符

等价函数写法

说明

A & B

A.intersection(B)

交集

`A

B`

A.union(B)

A - B

A.difference(B)

差集

A ^ B

A.symmetric_difference(B)

对称差集


七、集合关系运算

1. 子集与超集

A = {1, 2, 3}
B = {1, 2, 3, 4}

print(A.issubset(B))     # A 是 B 的子集 → True
print(B.issuperset(A))   # B 是 A 的超集 → True

2. 是否无交集

C = {5, 6}
print(A.isdisjoint(C))   # True(没有共同元素)

八、集合的应用场景

1. 去重(最常用)

nums = [1, 2, 2, 3, 3, 3, 4]
unique_nums = list(set(nums))
print(unique_nums)

结果:

[1, 2, 3, 4]

2. 求列表的共同部分

classA = ["Tom", "Jerry", "Amy"]
classB = ["Jerry", "Lucy", "Amy"]

common = set(classA) & set(classB)
print("两班共有:", common)

结果:

两班共有: {'Jerry', 'Amy'}

3. 检查是否含重复元素

words = ["apple", "banana", "apple", "orange"]
if len(words) == len(set(words)):
    print("没有重复元素")
else:
    print("有重复元素")

结果:

有重复元素

4. 用集合快速统计唯一字母

text = "hello world"
unique_letters = set(text)
print("不同字母:", unique_letters)
print("数量:", len(unique_letters))

九、集合推导式(Set Comprehension)

集合推导式是快速生成集合的一种方式。

squares = {x * x for x in range(1, 6)}
print(squares)

结果:

{1, 4, 9, 16, 25}

你也可以加条件:

even_squares = {x * x for x in range(1, 10) if x % 2 == 0}
print(even_squares)

结果:

{64, 4, 16, 36, 100}

十、综合练习题

例 1:科目统计

studentA = {"语文", "数学", "英语"}
studentB = {"数学", "英语", "科学"}

print("都选的科目:", studentA & studentB)
print("只A选的:", studentA - studentB)
print("总共涉及的科目:", studentA | studentB)

例 2:去除重复单词并排序

text = "apple orange banana apple orange"
unique_words = sorted(set(text.split()))
print(unique_words)

结果:

['apple', 'banana', 'orange']

例 3:判断是否为“全字母短句”

(英文练习用例——包含 26 个字母的句子)

sentence = "The quick brown fox jumps over the lazy dog"
letters = set(sentence.lower())
if set("abcdefghijklmnopqrstuvwxyz").issubset(letters):
    print("是全字母句!")
else:
    print("不是。")

十一、小结

操作

示例

说明

创建集合

{}

或 set()

无序、不重复

添加元素

add()

添加新元素

删除元素

remove()

/ discard()

删除指定元素

清空集合

clear()

删除所有元素

求交集

A & B

或 A.intersection(B)

两者共同元素

求并集

`A

B或

A.union(B)`

求差集

A - B

或 A.difference(B)

只属于 A 的元素

求对称差

A ^ B

只属于其中一个集合

判断关系

issubset()

/ issuperset()

判断子集或超集

应用场景

去重 / 求交 / 统计唯一值

非常实用!



十二、补充_冻结集合(frozenset)

(1)什么是冻结集合

frozenset 是集合(set)的“不可修改版本”。

  • 普通集合是 可变的(mutable):可以添加、删除元素。
  • 冻结集合是 不可变的(immutable):一旦创建,就不能更改。

📌 这意味着:

  • 它可以作为字典的 键(key);
  • 它可以作为另一个集合的 元素;
  • 但不能再使用 add()、remove() 等修改方法。

(2)创建冻结集合

使用内置函数 frozenset()。

a = frozenset([1, 2, 3, 3, 2])
print(a)

运行结果:

frozenset({1, 2, 3})

注意:和普通集合一样,frozenset() 会自动去重。


(3)冻结集合的特性

特性

是否支持

说明

添加 / 删除元素

❌ 不支持

不可修改

成员判断(in

)

✅ 支持

判断元素是否存在

集合运算(交并差等)

✅ 支持

返回新的集合对象

可作为集合元素

✅ 支持

因为它是不可变类型

可作为字典键

✅ 支持

因为它是可哈希(hashable)的


(4)冻结集合的使用示例

A = frozenset([1, 2, 3])
B = frozenset([3, 4, 5])

# 支持集合运算(结果是新的 frozenset)
print("交集:", A & B)
print("并集:", A | B)
print("差集:", A - B)

运行结果:

交集: frozenset({3})
并集: frozenset({1, 2, 3, 4, 5})
差集: frozenset({1, 2})

(5)frozenset 的应用场景

  1. 作为字典键(dict key)
    因为字典键必须是不可变类型。
cities = {
    frozenset(["北京", "上海"]): "一线城市",
    frozenset(["成都", "重庆"]): "新一线城市"
}
print(cities[frozenset(["成都", "重庆"])])

输出:

新一线城市
  1. 作为集合的元素
sets = {frozenset({1, 2}), frozenset({3, 4})}
print(sets)

输出:

{frozenset({1, 2}), frozenset({3, 4})}
  1. 保护数据安全
    当你想创建一个“不能被修改”的集合时,用 frozenset 比较安全。

(6)小结

对比项

set(可变集合)

frozenset(冻结集合)

是否可修改

✅ 可以添加/删除

❌ 不可修改

是否可哈希(可作字典键)

❌ 否

✅ 是

创建方式

{}

或 set()

frozenset()

常见用途

动态存储元素

固定集合、当作键或元素使用

✅ 学习提示

  • 集合看起来像“列表去重版”,但运算功能更强。
  • 重点记:&(交) |(并) -(差) ^(对称差) 四个符号。
  • 用集合检查、筛选、去重会非常高效。