少女祈祷中...
min blog

python学习第二天日记

第二天

Dict and Set

课程知识点速览

一、字典(Dict / Dictionary)

  1. 核心特性

    • 键值对(Key-Value)存储,底层基于哈希表实现,查找极快。

    • Key 的要求:必须唯一且为不可变类型(如字符串、数字、元组);列表和字典不能作为 Key。

    • Value 的要求:可以是任意类型,且允许重复。

  2. 创建方式{key: value}dict(key=value)

  3. 访问方法

    • d[key]:Key 不存在时会抛出 KeyError

    • d.get(key, default):安全取值,Key 不存在时返回默认值。

  4. 增删改

    • 新增 / 修改:d[key] = value

    • 删除:d.pop(key)del d[key]

  5. 合并运算符(Python 3.9+)

    • d1 | d2:合并并返回新字典,重复 Key 后者覆盖前者。

    • d1 |= d2:就地更新。

二、集合(Set)

  1. 核心特性

    • 无序、不重复元素的集合,元素必须是不可变类型。

    • 主要作用:数据去重快速成员判断(in

  2. 创建方式{1, 2, 3}set(iterable)(创建空集合必须用 set())。

  3. 元素操作

    • 添加:s.add(x)(单元素)、s.update(iterable)(批量)。

    • 删除:s.remove(x)(不存在会报错)、s.discard(x)(不存在不报错)。

  4. 集合运算

运算

运算符写法

方法写法

交集

s1 & s2

s1.intersection(s2)

并集

s1 \| s2

s1.union(s2)

差集

s1 - s2

s1.difference(s2)

对称差集

s1 ^ s2

s1.symmetric_difference(s2)

评论