寒假学习笔记1.28

一、学习目标
掌握字典(dict)的键值对结构与操作方法

理解集合(set)的特性及数学运算

学会使用字典推导式和集合推导式

能够根据不同场景选择合适的数据结构

理解哈希表原理(概念层面)

二、学习内容

  1. 字典(dict)—— 键值对映射
    创建字典:

python

空字典

empty_dict = {}
empty_dict2 = dict()

直接创建

student = {"name": "小明", "age": 18, "score": 90}
mixed_dict = {1: "整数键", "key": "字符串键", (1, 2): "元组键"} # 键必须是不可变类型

使用dict()构造函数

dict_from_list = dict([("a", 1), ("b", 2)]) # 列表套元组
dict_from_keys = dict.fromkeys(["name", "age"], None) # 统一初始值
访问与修改:

python

访问元素

print(student["name"]) # 直接访问,键不存在会报错
print(student.get("age")) # 使用get方法,键不存在返回None
print(student.get("grade", "未知")) # 指定默认值

修改和添加

student["age"] = 19 # 修改已有键
student["grade"] = "A" # 添加新键值对
student.update({"city": "北京", "age": 20}) # 批量更新

删除元素

del student["score"] # 删除指定键
value = student.pop("age") # 删除并返回值
student.clear() # 清空字典
字典常用方法:

python
info = {"name": "张三", "age": 20, "score": 85}

keys = info.keys() # 返回所有键
values = info.values() # 返回所有值
items = info.items() # 返回所有键值对

for key in info.keys():
print(key)

for key, value in info.items():
print(f"{key}: {value}")

检查键是否存在

if "name" in info:
print("姓名存在")
2. 集合(set)—— 无序不重复元素
创建集合:

python

空集合(注意不能用{},这是空字典)

empty_set = set()

创建集合

numbers = {1, 2, 3, 4, 5}
chars = set("hello") # 输出:{'h', 'e', 'l', 'o'}(去重且无序)

从列表转换

lst = [1, 2, 2, 3, 3, 3]
unique_set = set(lst) # 输出:{1, 2, 3}
集合操作:

python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

添加删除

A.add(5) # 添加单个元素
A.update([6, 7]) # 添加多个元素
A.remove(1) # 删除元素,不存在则报错
A.discard(10) # 删除元素,不存在不报错
element = A.pop() # 随机删除并返回一个元素

集合运算

print(A | B) # 并集:{1, 2, 3, 4, 5, 6}
print(A & B) # 交集:{3, 4}
print(A - B) # 差集:{1, 2}
print(A ^ B) # 对称差集:{1, 2, 5, 6}

集合关系

print({1, 2} <= {1, 2, 3}) # 子集判断:True
print(A.isdisjoint({7, 8})) # 是否无交集:True
3. 推导式(Comprehensions)
字典推导式:

python

创建平方字典

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

输出:

条件过滤

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

反转键值对

original = {"a": 1, "b": 2}
reversed_dict = {v: k for k, v in original.items()}
集合推导式:

python

创建偶数集合

evens = {x for x in range(10) if x % 2 == 0}

去重并转换

words = ["hello", "world", "hello", "python"]
first_chars = {word[0] for word in words}
4. 数据结构选择指南
需求 推荐数据结构 原因
有序、可重复、可变 列表 支持索引、切片,灵活修改
有序、可重复、不可变 元组 保护数据完整性,可作为字典键
键值对映射 字典 快速查找,数据关联性强
去重、集合运算 集合 自动去重,支持数学运算
仅存储键 字典(值设为None)或集合 根据是否需要额外信息决定
三、实践练习
练习1:单词统计器
python

统计一段文本中每个单词的出现次数

text = "apple banana apple orange banana apple"
words = text.split()

方法1:使用字典手动统计

word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

方法2:使用get方法简化

word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1

方法3:使用collections模块

from collections import Counter
word_count = Counter(words)

输出结果

for word, count in word_count.items():
print(f"{word}: {count}")
练习2:学生通讯录管理系统
python

使用字典管理学生信息

address_book = {}

while True:
print("\n=== 学生通讯录管理系统 ===")
print("1. 添加学生")
print("2. 查找学生")
print("3. 删除学生")
print("4. 显示所有学生")
print("5. 统计学生数量")
print("6. 退出")

choice = input("请选择操作:")

if choice == "1":
    student_id = input("请输入学号:")
    if student_id in address_book:
        print("该学号已存在!")
    else:
        name = input("请输入姓名:")
        phone = input("请输入电话:")
        address_book[student_id] = {"name": name, "phone": phone}
        print("添加成功!")

elif choice == "2":
    student_id = input("请输入要查找的学号:")
    if student_id in address_book:
        info = address_book[student_id]
        print(f"姓名:{info['name']},电话:{info['phone']}")
    else:
        print("学号不存在!")

elif choice == "3":
    student_id = input("请输入要删除的学号:")
    if student_id in address_book:
        del address_book[student_id]
        print("删除成功!")
    else:
        print("学号不存在!")

elif choice == "4":
    if address_book:
        print("\n所有学生信息:")
        for sid, info in address_book.items():
            print(f"学号:{sid},姓名:{info['name']},电话:{info['phone']}")
    else:
        print("通讯录为空!")

elif choice == "5":
    print(f"共有 {len(address_book)} 名学生")

elif choice == "6":
    print("退出系统!")
    break

练习3:集合运算应用
python

选修课统计

math_students = {"小明", "小红", "小刚"}
physics_students = {"小红", "小刚", "小芳"}
english_students = {"小明", "小芳", "小强"}

选数学或物理的学生

math_or_physics = math_students | physics_students
print(f"选数学或物理的学生:{math_or_physics}")

三科都选的学生

all_courses = math_students & physics_students & english_students
print(f"三科都选的学生:{all_courses}")

只选一科的学生

only_math = math_students - physics_students - english_students
print(f"只选数学的学生:{only_math}")

选了两科的学生

two_courses = (math_students & physics_students) |
(math_students & english_students) |
(physics_students & english_students)
print(f"选了两科的学生:{two_courses}")
四、遇到的问题与解决
问题:字典键必须是不可变类型

解决:列表不能作为字典键,可使用元组或字符串

理解:因为字典基于哈希表,键需要可哈希(不可变)

问题:集合无序性导致的困惑

解决:不依赖集合元素的顺序,需要有序时使用列表或元组

注意:Python 3.7+中字典保持插入顺序,但集合仍然无序

问题:{}创建的是空字典而非空集合

解决:使用set()创建空集合,{}创建空字典

记忆:集合需要显式调用set()构造函数

问题:字典访问不存在的键导致KeyError

解决:使用get()方法或先检查键是否存在

技巧:使用setdefault()方法

python

如果键不存在,设置默认值并返回

count = word_dict.setdefault(word, 0)
word_dict[word] += 1
五、学习总结
字典是Python中极其重要的数据结构,基于哈希表实现快速查找

集合主要用于去重和数学运算,同样基于哈希表

掌握了四种推导式:列表、字典、集合、生成器(明天学习)

理解了不同数据结构的特点和适用场景

能够根据实际问题选择合适的数据结构

六、明日计划
学习函数定义与调用

理解参数传递(位置参数、关键字参数、默认参数)

掌握返回值与作用域概念

学习lambda表达式

尝试模块化编程

posted @ 2026-01-30 21:56  头发少的文不识  阅读(5)  评论(0)    收藏  举报