摘要:集合(set)不仅能去重、做集合运算,还能在许多高阶场景中提升代码的简洁性与效率。
集合(set)不仅能去重、做集合运算,还能在许多高阶场景中提升代码的简洁性与效率。
下面介绍一些进阶技巧与常见应用。
一、去重技巧
1、快速去重(不保序)
nums = [1, 2, 2, 3, 4, 4, 5]unique = list(set(nums))print(unique) # [1, 2, 3, 4, 5](顺序不保证)2、去重并保序
nums = [1, 2, 2, 3, 4, 4, 5]unique_stable = list(dict.fromkeys(nums))print(unique_stable) # [1, 2, 3, 4, 5]二、成员测试
集合的 in 查询是基于哈希表实现的,平均复杂度 O(1),而列表则是 O(n)。这意味着当数据规模很大时,集合在查找方面更高效。
data = set(range(1_000_000))print(999_999 in data) # True,查找速度快三、集合运算的实战应用
1、交集:找共同元素
friends_A = {"Tom", "Alice", "Bob"}friends_B = {"Bob", "Cathy", "Alice"}common = friends_A & friends_Bprint(common) # {'Alice', 'Bob'}2、差集:找独有元素
recommend = friends_B - friends_Aprint(recommend) # {'Cathy'}3、并集:合并多个集合
all_users = set.union(friends_A, friends_B, {"David"})print(all_users) # {'Tom', 'Alice', 'Bob', 'Cathy', 'David'}四、不可变集合
是 Python 内置的不可变集合类型构造函数。它与 set 类似,但一旦创建,其元素就不能被添加、删除或修改,因此可以作为字典的键或其他集合的元素。
1、作为字典键
fs1 = frozenset([1, 2])fs2 = frozenset([2, 3])d = {fs1: "A", fs2: "B"}print(d) # {frozenset({1, 2}): 'A', frozenset({2, 3}): 'B'}2、作为集合元素(集合嵌套)
s = {frozenset([1, 2]), frozenset([3, 4])}print(s) # {frozenset({1, 2}), frozenset({3, 4})}五、与内置函数搭配
1、 + set:筛选唯一元素
适合清理数据时只保留符合条件的集合。
nums = [1, 2, 2, 3, 4, 5, 6]even_set = set(filter(lambda x: x % 2 == 0, nums))print(even_set) # {2, 4, 6}2、+ set :映射后取唯一值
适合收集特征值,如单词长度集合。
words = ["apple", "banana", "cherry", "banana"]lengths = set(map(len, words))print(lengths) # {5, 6}3、+ set :唯一配对集合
适合构建唯一 (name, score) 集合。
names = ["Alice", "Bob", "Cathy", "Alice"]scores = [90, 85, 90, 90]pairs = set(zip(names, scores))print(pairs) # {('Bob', 85), ('Cathy', 90), ('Alice', 90)}六、模式匹配中的应用
Python 3.10 引入 结构,支持匹配集合内容。
def describe(s: set[int]) -> str:match s:case {1, 2, 3}:return "Full set {1,2,3}"case {1, 2}:return "Partial set {1,2}"case _:return "Other"print(describe({1, 2, 3})) # Full set {1,2,3}小结
去重技巧:set 去重;dict.fromkeys 保序去重
高效查找:in 操作 O(1)
运算应用:交集(共同)、差集(独有)、并集(合并)
frozenset:可作为字典键或集合元素
函数式搭配:结合 filter、map、zip 快速生成唯一集合
模式匹配:Python 3.10+ 可直接匹配集合内容
“点赞有美意,赞赏是鼓励”
来源:静静趣味教学视频