Python 学习教程 · 第4课:数据结构

对应官方教程第 5 章。上一课用 (状态码, 工时) 两个值表示一条日志。这一课给每条日志加上字段名,用 字典表示单条记录、列表保存多条记录、集合去重,最后按服务汇总错误数和工时。

建议先学列表、字典、集合和遍历,再回头学嵌套推导式、队列和序列比较。把每段示例单独复制到 VS Code 的 practice.py,在文件所在目录的 PowerShell 中运行 py -3.14 .\practice.py。

数据结构 示例 在日志里的用途
列表 list [502, 404, 502] 按顺序保存多个值,允许重复
元组 tuple ("gateway", 502) 把固定位置的一组值放在一起
集合 set {404, 502} 去重、检查是否出现过
字典 dict {"service": "gateway", "code": 502} 按字段名取值,或按服务名汇总

5.1 列表:添加、删除、排序

操作 作用
append(x) 在末尾加一个元素
extend(values) 把多个元素逐个加入末尾
insert(i, x) 在下标 i 处插入
remove(x) 删除第一个等于 x 的元素,找不到会报 ValueError
pop(i) 删除并返回指定位置的元素,省略下标时取最后一个
index(x)、count(x) 查第一个匹配的位置、统计出现次数
sort()、reverse() 就地排序、就地反转
copy()、clear() 创建浅拷贝、清空原列表
python 复制代码
codes = [502, 404]
codes.append(504)
codes.extend([500, 503])
print(codes)           # [502, 404, 504, 500, 503]

ordered = sorted(codes)
print(ordered)         # [404, 500, 502, 503, 504]
print(codes[0])        # 502

append([500, 503]) 会把整张小列表当成一个元素。extend([500, 503]) 会加入两个数字。sorted(codes) 返回新列表,和 JS 中需要保留原数组时的思路相近。codes.sort() 修改原列表并返回 None。

5.1.1 堆栈与 5.1.2 队列

python 复制代码
from collections import deque

history = ["确认样例", "联调筛选"]
history.append("复核卡片")
print(history.pop())  # 复核卡片

pending = deque(["告警 A", "告警 B"])
pending.append("告警 C")
print(pending.popleft())  # 告警 A

堆栈是后进先出 ,像撤销历史,最后完成的动作先取出。队列是先进先出 ,像依次处理告警。deque.popleft() 适合反复从左边取元素。普通列表的 pop(0) 会移动后续元素。

5.1.3 列表推导式

python 复制代码
codes = [200, 404, 502, 504]
server_errors = [code for code in codes if 500 <= code < 600]
print(server_errors)  # [502, 504]

读法是「遍历 codes,满足筛选条件时,把当前 code 放进新列表」。等价于先创建空列表,再在 for 循环里判断并 append。前端可以类比 filter。开头换成 str(code),就会同时把筛选出的数字转为字符串,类似先 filter 再 map。

5.1.4 嵌套推导式与 5.1.5 解包

python 复制代码
batches = [[502, 504], [], [404]]

flat = [code for batch in batches for code in batch]
print(flat)  # [502, 504, 404]

print([200, *flat, 503])  # [200, 502, 504, 404, 503]

matrix = [[1, 2, 3], [4, 5, 6]]
columns = [[row[index] for row in matrix] for index in range(3)]
print(columns)  # [[1, 4], [2, 5], [3, 6]]

第一行推导式按书写顺序读两个 for:先取一批,再取批里的每个状态码。矩阵例子中,外层每选一个列下标,内层从各行取这个下标的值,得到一列。*flat 在普通列表字面量中逐个展开元素,和 JS 的 ...flat 接近。

原文还展示了 Python 3.15 的推导式解包写法 [*batch for batch in batches]。你目前用 Python 3.14.5,练习时用上面两个 for 的版本。

5.2 del:按位置删除

python 复制代码
codes = [200, 404, 502, 504]
del codes[0]
print(codes)  # [404, 502, 504]

del codes[1:]
print(codes)  # [404]

del 可以删除单个下标或整个切片。pop 还会给调用方返回被删掉的值。del codes 会删除变量名绑定,之后直接访问该名字会报 NameError。

5.3 元组和序列:固定的一组值

python 复制代码
record = ("gateway", 502)
service, code = record
print(service, code)       # gateway 502
print(type((502,)).__name__)  # tuple

右边是两个元素,左边也要有两个变量,这就是序列解包 。单元素元组要加逗号,(502) 只是带括号的整数。元组和列表都能索引、切片。元组里的元素位置不能重新赋值,但如果某个元素本身是列表,仍然可以修改那个列表。

5.4 集合:去重与成员检查

python 复制代码
today = {502, 504}
yesterday = {404, 502}

print(sorted(set([502, 502, 504])))  # [502, 504]
print(502 in today)                 # True
print(sorted(today | yesterday))    # [404, 502, 504]
print(sorted(today & yesterday))    # [502]
print(sorted(today - yesterday))    # [504]
print(sorted(today ^ yesterday))    # [404, 504]

| 是并集,& 是交集,- 是差集,^ 取只出现在其中一边的元素。空集合写 set(),{} 是空字典。集合没有可依赖的遍历顺序。如果既要去重又要保留首次出现的顺序,可以用 list(dict.fromkeys(codes))。

5.5 字典:用字段名取值,按服务分组

python 复制代码
log = {"service": "gateway", "code": 502}
log["minutes"] = 35
print(log["service"])              # gateway
print(log.get("trace_id", "缺失")) # 缺失
print("code" in log)               # True

minutes_by_service = dict([("gateway", 35), ("auth", 20)])
doubled = {name: value * 2 for name, value in minutes_by_service.items()}
print(doubled)  # {'gateway': 70, 'auth': 40}

字典用键访问值,写法类似 JS 的对象索引。log["trace_id"] 在字段缺失时会报 KeyError,get 可以给缺失键提供默认值。in 检查的是键。写入已有键会替换对应的值,字典保留键的插入顺序。

5.6 循环技巧:看你同时需要哪些值

python 复制代码
services = ["gateway", "auth"]
counts = [2, 1]

for number, service in enumerate(services, start=1):
    print(number, service)  # 1 gateway,然后 2 auth

for service, count in zip(services, counts):
    print(service, count)   # gateway 2,然后 auth 1

totals = {"gateway": 80, "auth": 20}
for service, minutes in totals.items():
    print(service, minutes)  # gateway 80,然后 auth 20

print(list(reversed(services)))  # ['auth', 'gateway']

enumerate 同时给序号和值,zip 把多个序列的对应位置配成对,items() 同时给字典的键和值。zip 默认在较短的序列结束时停下。如果业务上要求两边长度相同,可以写 zip(services, counts, strict=True),长度不一致会报错。遍历期间要筛掉一部分元素时,可以用推导式创建新列表,避免边遍历边改变原列表的长度。

5.7 条件:成员关系、对象身份、短路

python 复制代码
code = 502
log = {"code": code}

print(500 <= code < 600)                 # True
print("minutes" in log and log["minutes"] > 0)  # False
print(log.get("service") or "未知服务")         # 未知服务

first = [502]
second = [502]
print(first == second)  # True,内容相等
print(first is second)  # False,两个独立列表
  • in 和 not in 检查值是否在容器里。判断缺失值 None 常用 is None。
  • and 左边为假就跳过右边,所以字段缺失时,上例不会访问 log["minutes"]。
  • or 左边为真就返回左边,否则求右边。用它取默认值时,空字符串和数字 0 也会触发默认值。若只想处理 None,要单独判断。
  • not 把条件取反。表达式内赋值用 :=,初学时也可以先单独赋值,再写判断。

5.8 序列比较:从左往右比

python 复制代码
print((502, 35) < (502, 45))  # True
print((502,) < (502, 35))     # True
print([404, 504] < [502])    # True

先比较第一项,相同再比较下一项。(502, 35) 和 (502, 45) 的状态码相同,由工时决定顺序。如果一个序列是另一个开头的一部分,较短的排在前面。字符串也逐字符比较。混用无法排序的值,例如整数和字符串,会在执行顺序比较时报 TypeError。

实战:按服务汇总 AIOps 错误日志

用和上一课一样的 4 条示例记录,给每条加上服务名。输出错误数、处理工时和去重后的状态码。

python 复制代码
def summarize_errors(logs):
    summaries = {}

    for log in logs:
        code = log["code"]
        if not 400 <= code < 600:
            continue

        service = log["service"]
        if service not in summaries:
            summaries[service] = {"count": 0, "minutes": 0, "codes": set()}

        summary = summaries[service]
        summary["count"] += 1
        summary["minutes"] += log["minutes"]
        summary["codes"].add(code)

    return summaries


logs = [
    {"service": "gateway", "code": 200, "minutes": 10},
    {"service": "auth", "code": 404, "minutes": 20},
    {"service": "gateway", "code": 502, "minutes": 35},
    {"service": "gateway", "code": 504, "minutes": 45},
]

summaries = summarize_errors(logs)
for service in sorted(summaries):
    summary = summaries[service]
    codes = sorted(summary["codes"])
    print(f"{service}:{summary['count']} 条,{summary['minutes']} 分钟,{codes}")
text 复制代码
auth:1 条,20 分钟,[404]
gateway:2 条,80 分钟,[502, 504]

第一条 200 被跳过。处理到 502 时,程序首次为 gateway 创建汇总。下一条 504 继续更新同一份字典。集合只保存不同的状态码,数量和工时仍按每条日志累加。如果以后要通过接口返回 JSON,可以先把集合转成列表,例如 sorted(summary["codes"])。

自测修改 预期结果
再加一条 gateway 的 502 日志,耗时 5 分钟 gateway 变为 3 条、85 分钟,状态码仍是 [502, 504]
改成只收集 5xx 只输出 gateway,2 条、80 分钟
传入空列表 函数返回空字典,终端汇总循环没有输出

学完后试着不看代码回答:为什么日志用字典?为什么状态码用集合?为什么要等输出时再对集合排序?

原文:Python 官方教程 · 数据结构

相关推荐
honker_X14 分钟前
Python字符串全攻略:从入门到精通
开发语言·python
贾公子27 分钟前
异步检测的轮询与超时——别把「还没好」当成「失败了」
后端·python
吃我一窝jio31 分钟前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
欢乐马87912 小时前
优化|MPSolver 和 pywraplp 到底谁是谁?一次讲清 OR-Tools 的三层结构
python
mengge.cloud3 小时前
Python基础保姆级!从入门到入土
开发语言·python·云原生·pygame
星落梦生3 小时前
Docker学习(11)
学习·docker·容器
qq_158895411117 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
郝学胜-神的一滴16 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
学无止境小袁同学18 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli