Day 4 · 列表、元组、集合、字典

Week 1 · Day 4 / 56 · 预计 2 小时 · 返回大纲
⚠️ 今天是最重要的一天! 这四个数据结构是 Python 的基石,后面所有内容都建立在它们之上。列表推导式更是 Python 区别于其他语言的核心特性。

一、列表 List(复习 + 深入)

列表是 Python 最常用的数据结构,类似 JS 的 Array。

1.1 创建和访问

# 创建
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]   # Python 列表可以混合类型
empty = []

# 访问
fruits[0]       # "apple"
fruits[-1]      # "orange"(负数从末尾)
fruits[0:2]     # ["apple", "banana"](切片)
fruits[:2]      # ["apple", "banana"]
fruits[1:]      # ["banana", "orange"]
fruits[::2]     # ["apple", "orange"](步长 2)

# 长度
len(fruits)     # 3

1.2 修改和操作

fruits = ["apple", "banana", "orange"]

# 增
fruits.append("grape")        # 末尾添加
fruits.insert(1, "mango")     # 指定位置插入

# 删
fruits.remove("banana")       # 按值删除
del fruits[0]                 # 按索引删除
fruits.pop()                  # 删除并返回末尾
fruits.pop(0)                 # 删除并返回指定位置

# 改
fruits[0] = "pear"

# 查
"apple" in fruits             # True
fruits.index("orange")        # 索引位置
fruits.count("apple")         # 出现次数

# 排序
fruits.sort()                 # 原地排序
fruits.sort(reverse=True)     # 降序
sorted(fruits)               # 返回新列表(不修改原列表)
fruits.reverse()              # 原地反转
reversed(fruits)              # 返回反转迭代器

# 拼接
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2      # [1, 2, 3, 4]
list1.extend(list2)           # 原地扩展

1.3 列表的坑

# 坑 1:复制列表(浅拷贝)
a = [1, 2, 3]
b = a                # b 和 a 指向同一个列表!
b[0] = 999
print(a)             # [999, 2, 3] ← a 也变了!

# 正确复制
b = a.copy()         # 浅拷贝
b = a[:]             # 切片也是复制
b = list(a)          # 构造函数

# 坑 2:循环中删除元素
items = [1, 2, 3, 4, 5]
for item in items:
    if item % 2 == 0:
        items.remove(item)   # 危险!跳过元素

# 正确做法
items = [item for item in items if item % 2 != 0]  # 列表推导式

二、元组 Tuple

元组是不可变的列表,创建后不能修改。

JavaScript
// JS 没有元组
// 数组可变
const point = [10, 20];
point[0] = 99;  // 可以
Python Tuple
# 元组不可变
point = (10, 20)
point[0] = 99   # TypeError!

# 单元素元组注意逗号
single = (42,)    # 是元组
not_tuple = (42)  # 只是 int

# 不需要括号
point = 10, 20

# 解包
x, y = point
x, y, *rest = (1, 2, 3, 4, 5)
# 元组的用途
# 1. 表示固定数据(坐标、颜色 RGB)
point = (100, 200)
color = (255, 128, 0)

# 2. 函数返回多个值
def get_user():
    return "Alice", 25, "北京"

name, age, city = get_user()

# 3. 字典的 key(列表不能做 key)
locations = {
    (39.9, 116.4): "北京",
    (31.2, 121.5): "上海",
}

# 元组 vs 列表的选择
# 数据不需要改 → 元组(更快、更安全)
# 数据需要改 → 列表

三、集合 Set

集合是无序、不重复的元素集合。

JavaScript Set
const set = new Set([1, 2, 2, 3, 3]);
// Set(3) {1, 2, 3}

set.add(4);
set.delete(1);
set.has(2);  // true

// 转数组
[...set];
Python Set
s = {1, 2, 2, 3, 3}
# {1, 2, 3}  自动去重

s.add(4)
s.remove(1)
2 in s    # True

# 空集合
empty = set()   # 不是 {}(那是字典)

# 列表去重
list(set([1, 2, 2, 3]))  # [1, 2, 3]
# 集合运算(Python 特色!)
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a & b       # 交集 {3, 4}
a | b       # 并集 {1, 2, 3, 4, 5, 6}
a - b       # 差集 {1, 2}
a ^ b       # 对称差集 {1, 2, 5, 6}

# 实际用途
# 找出两个列表的共同元素
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = set(list1) & set(list2)   # {3, 4}

四、字典 Dict(重点!)

字典是 Python 最强大的数据结构,类似 JS 的 Object/Map。

4.1 创建和访问

JavaScript Object
const user = {
    name: "Alice",
    age: 25,
    city: "北京"
};

user.name;          // "Alice"
user["name"];       // "Alice"
user.job;           // undefined

// 遍历
Object.keys(user);     // ["name", "age", "city"]
Object.values(user);   // ["Alice", 25, "北京"]
Object.entries(user);  // [["name","Alice"], ...]

// 删除
delete user.age;
Python Dict
user = {
    "name": "Alice",
    "age": 25,
    "city": "北京"
}

user["name"]        # "Alice"
user.get("job")     # None(不报错)
user.get("job", "未知")  # 默认值

# 遍历
user.keys()         # dict_keys(['name', 'age', 'city'])
user.values()       # dict_values(['Alice', 25, '北京'])
user.items()        # dict_items([('name','Alice'), ...])

# 删除
del user["age"]

4.2 常用操作

user = {"name": "Alice", "age": 25}

# 添加/修改
user["city"] = "北京"          # 添加
user["age"] = 26               # 修改

# 安全获取
user.get("job", "未知")         # key 不存在时返回默认值

# 批量更新
user.update({"age": 26, "city": "上海", "job": "工程师"})

# 遍历
for key in user:               # 只遍历 key
    print(key, user[key])

for key, value in user.items():  # 同时遍历 key 和 value
    print(f"{key}: {value}")

for value in user.values():    # 只遍历 value
    print(value)

# 合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}    # {"a":1, "b":2, "c":3, "d":4}

4.3 字典嵌套(模拟 JSON)

# 字典可以嵌套,完美对应 JSON
response = {
    "code": 200,
    "data": {
        "user": {
            "id": 1,
            "name": "Alice",
            "skills": ["Python", "JS", "SQL"]
        },
        "settings": {
            "notifications": True,
            "theme": "dark"
        }
    }
}

# 访问嵌套
response["data"]["user"]["name"]           # "Alice"
response["data"]["user"]["skills"][0]     # "Python"

# 安全访问(避免 KeyError)
response.get("data", {}).get("user", {}).get("name", "匿名")

五、列表推导式(Python 核心!)

这是 Python 最重要的特性之一,必须掌握! 列表推导式是用一行代码生成列表的优雅方式。

5.1 基本语法

JavaScript map + filter
// map
const doubled = arr.map(x => x * 2);

// filter
const evens = arr.filter(x => x % 2 === 0);

// map + filter
const result = arr
    .filter(x => x > 0)
    .map(x => x * 2);
Python 列表推导式
# map 等价
doubled = [x * 2 for x in arr]

# filter 等价
evens = [x for x in arr if x % 2 == 0]

# map + filter
result = [x * 2 for x in arr if x > 0]

5.2 各种写法

# 1. 基本形式:[表达式 for 变量 in 可迭代]
[x * 2 for x in range(5)]       # [0, 2, 4, 6, 8]

# 2. 带条件:[表达式 for 变量 in 可迭代 if 条件]
[x for x in range(10) if x % 2 == 0]   # [0, 2, 4, 6, 8]

# 3. 多变量(解包)
pairs = [(1, "a"), (2, "b"), (3, "c")]
[str_num + letter for str_num, letter in pairs]
# ["1a", "2b", "3c"]

# 4. 嵌套循环
matrix = [[1, 2], [3, 4], [5, 6]]
[num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
# 等价于:
# for row in matrix:
#     for num in row:
#         ...

# 5. 带 else(条件表达式)
[x if x > 0 else 0 for x in [-1, 2, -3, 4]]
# [0, 2, 0, 4]

# 6. 字符串操作
words = ["Hello", "World", "Python"]
[w.upper() for w in words]      # ["HELLO", "WORLD", "PYTHON"]
[len(w) for w in words]         # [5, 5, 6]

5.3 字典推导式和集合推导式

# 字典推导式
{x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 条件字典推导式
{x: x**2 for x in range(5) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16}

# 集合推导式
{x**2 for x in [-2, -1, 0, 1, 2]}
# {0, 1, 4}

# 实用:字典键值反转
original = {"a": 1, "b": 2, "c": 3}
reversed_dict = {v: k for k, v in original.items()}
# {1: "a", 2: "b", 3: "c"}
💡 性能: 列表推导式通常比 for 循环 + append 更快,因为它在 Python 层面是优化过的。

六、解包技巧

# 列表/元组解包
a, b, c = [1, 2, 3]
a, b, c = (1, 2, 3)

# * 收集剩余
first, *rest = [1, 2, 3, 4, 5]
# first=1, rest=[2, 3, 4, 5]

*init, last = [1, 2, 3, 4, 5]
# init=[1, 2, 3, 4], last=5

first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2, 3, 4], last=5

# 交换变量
a, b = 1, 2
a, b = b, a    # 不需要临时变量

# 函数调用解包
def func(a, b, c):
    print(a, b, c)

args = [1, 2, 3]
func(*args)          # 1 2 3

kwargs = {"a": 1, "b": 2, "c": 3}
func(**kwargs)       # 1 2 3

七、实战:词频统计器

创建 day4.py,用今天学的所有知识:

#!/usr/bin/env python3
"""Day 4 练习:词频统计器"""

def count_words(text):
    """统计文本中每个单词出现的次数"""
    # 转小写、分词
    words = text.lower().split()
    
    # 用字典统计
    freq = {}
    for word in words:
        # 去除标点
        word = word.strip(".,!?;:\"'")
        freq[word] = freq.get(word, 0) + 1
    
    return freq

def top_n(freq, n=3):
    """返回出现次数最多的 n 个词"""
    # 用 sorted + 字典 items
    sorted_items = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    return sorted_items[:n]

def main():
    text = """
    Python is a great programming language.
    Python is easy to learn.
    JavaScript is also great, but Python is simpler.
    I love Python programming!
    """
    
    print("=== 原文 ===")
    print(text.strip())
    
    # 词频统计
    freq = count_words(text)
    print("\n=== 词频统计 ===")
    for word, count in freq.items():
        print(f"  {word}: {count}")
    
    # 高频词
    print("\n=== 高频词 Top 3 ===")
    for word, count in top_n(freq, 3):
        print(f"  {word}: {count} 次")
    
    # 用列表推导式:找出出现 2 次以上的词
    repeated = {word: count for word, count in freq.items() if count >= 2}
    print(f"\n=== 出现 2 次以上的词 ===")
    print(f"  {repeated}")

if __name__ == "__main__":
    main()

八、动手练习

练习 1:列表推导式转换
用列表推导式完成以下任务
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 要求:
# 1. 所有数字的平方
# 2. 只保留偶数的平方
# 3. 大于 5 的数字 × 2,否则 × 0(用 if/else 表达式)
# 4. 字符串列表:["1", "2", ..., "10"](数字转字符串)

# 你的代码:
查看答案
参考答案
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 1. 所有数字的平方
squares = [x ** 2 for x in nums]
print(f"平方:{squares}")

# 2. 只保留偶数的平方
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(f"偶数平方:{even_squares}")

# 3. 大于 5 的数字 × 2,否则 × 0
transformed = [x * 2 if x > 5 else 0 for x in nums]
print(f"转换:{transformed}")

# 4. 数字转字符串
str_nums = [str(x) for x in nums]
print(f"字符串:{str_nums}")
练习 2:字典操作
处理学生成绩字典
scores = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78,
    "Diana": 90,
    "Eve": 65
}

# 要求:
# 1. 计算平均分
# 2. 找出最高分的学生
# 3. 找出及格(>=60)的学生名单
# 4. 用字典推导式创建新字典:{"Alice": "A", ...}(>=80 为 A,>=60 为 B,否则为 C)
# 5. 按分数从高到低排序输出

# 你的代码:
查看答案
参考答案
scores = {
    "Alice": 85, "Bob": 92, "Charlie": 78, "Diana": 90, "Eve": 65
}

# 1. 平均分
average = sum(scores.values()) / len(scores)
print(f"平均分:{average:.1f}")

# 2. 最高分学生
top_student = max(scores, key=scores.get)
print(f"最高分:{top_student}({scores[top_student]} 分)")

# 3. 及格学生
passed = [name for name, score in scores.items() if score >= 60]
print(f"及格学生:{passed}")

# 4. 等级字典
grades = {
    name: "A" if score >= 80 else ("B" if score >= 60 else "C")
    for name, score in scores.items()
}
print(f"等级:{grades}")

# 5. 按分数排序
for name, score in sorted(scores.items(), key=lambda x: x[1], reverse=True):
    print(f"  {name}: {score}")
练习 3:集合运算
用集合运算分析两组数据
frontend = {"HTML", "CSS", "JS", "React", "Vue"}
backend = {"Python", "FastAPI", "SQL", "Docker", "JS"}

# 要求:
# 1. 两个领域都需要的技能(交集)
# 2. 所有技能(并集)
# 3. 只在前端不需要后端的技能(差集)
# 4. 只在一个领域需要的技能(对称差集)
# 5. 判断 "JS" 是否是共同技能

# 你的代码:
查看答案
参考答案
frontend = {"HTML", "CSS", "JS", "React", "Vue"}
backend = {"Python", "FastAPI", "SQL", "Docker", "JS"}

# 1. 交集
common = frontend & backend
print(f"共同技能:{common}")

# 2. 并集
all_skills = frontend | backend
print(f"所有技能:{all_skills}")

# 3. 差集
only_frontend = frontend - backend
print(f"只前端:{only_frontend}")

# 4. 对称差集
only_one = frontend ^ backend
print(f"只在一个领域:{only_one}")

# 5. 判断
print(f"JS 是共同技能:{'JS' in common}")
练习 4:嵌套数据处理
处理 API 返回的嵌套 JSON 数据
users = [
    {"name": "Alice", "age": 25, "tags": ["admin", "editor"], "active": True},
    {"name": "Bob", "age": 30, "tags": ["viewer"], "active": False},
    {"name": "Charlie", "age": 28, "tags": ["editor", "viewer"], "active": True},
]

# 要求:
# 1. 找出所有活跃用户(active=True)的名字
# 2. 找出所有 tags 中包含 "editor" 的用户
# 3. 计算所有用户的平均年龄
# 4. 收集所有出现过的 tag(去重)
# 5. 用字典推导式创建 {名字: 年龄} 的映射

# 你的代码:
查看答案
参考答案
users = [
    {"name": "Alice", "age": 25, "tags": ["admin", "editor"], "active": True},
    {"name": "Bob", "age": 30, "tags": ["viewer"], "active": False},
    {"name": "Charlie", "age": 28, "tags": ["editor", "viewer"], "active": True},
]

# 1. 活跃用户
active_names = [u["name"] for u in users if u["active"]]
print(f"活跃用户:{active_names}")

# 2. 包含 editor 标签的用户
editors = [u["name"] for u in users if "editor" in u["tags"]]
print(f"Editor:{editors}")

# 3. 平均年龄
avg_age = sum(u["age"] for u in users) / len(users)
print(f"平均年龄:{avg_age:.1f}")

# 4. 所有 tag(去重)
all_tags = set()
for u in users:
    all_tags.update(u["tags"])
print(f"所有标签:{all_tags}")

# 5. {名字: 年龄}
name_age = {u["name"]: u["age"] for u in users}
print(f"名字-年龄:{name_age}")

九、打卡验收

熟练操作列表:增删改查、切片、排序
理解元组不可变,知道什么时候用元组 vs 列表
会用集合做去重和交并差运算
熟练操作字典:访问、遍历、嵌套、get 默认值
掌握列表推导式:带条件、带 else、嵌套循环
会用字典推导式和集合推导式
理解解包技巧:*rest、交换变量
完成 4 个动手练习,代码能跑通
打卡方式: 全部勾选后,告诉我 "Day 4 打卡",并贴出你的代码,我帮你检查。
明天预告(Day 5): 字符串高级操作、f-string 格式化、正则表达式入门。