第一章 Python语言概述与生态体系

1.3 Python在工业界的应用场景
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strprice: float@app.post("/items/")
async def create_item(item: Item):return {"item_name": item.name, "adjusted_price": item.price*1.1}
1.4 Python版本选择指南
if (n := len([1,2,3])) > 2:print(f"List length {n} is greater than 2")
第三章 Python核心语法精解
3.2 数据结构进阶操作
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2
matrix = [[1,2], [3,4], [5,6]]
flatten = [num for row in matrix for num in row]
3.4 上下文管理器原理
class DatabaseConnection:def __init__(self, db_name):self.db_name = db_namedef __enter__(self):self.conn = sqlite3.connect(self.db_name)return self.conndef __exit__(self, exc_type, exc_val, exc_tb):self.conn.close()if exc_type:print(f"Error occurred: {exc_val}")
with DatabaseConnection("test.db") as conn:cursor = conn.cursor()cursor.execute("SELECT * FROM users")
第六章 异常处理与调试技巧
6.2 调试器高级用法
import pdbdef complex_calculation(a, b):result = 0for i in range(a):pdb.set_trace() result += (i * b) ** 2return result
第十章 数据分析与可视化
10.1 Pandas数据处理实战
import pandas as pd
import numpy as np
date_rng = pd.date_range(start='2023-01-01', end='2023-01-10', freq='D')
df = pd.DataFrame({'date': date_rng,'value': np.random.randn(len(date_rng)).cumsum()
})
df['3_day_avg'] = df['value'].rolling(window=3).mean()
pivot = pd.pivot_table(df, values='value',index=df['date'].dt.day,aggfunc=['mean', 'max'])
10.2 Matplotlib可视化进阶
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.sin(x**2 + y**2)ax.scatter(x, y, z, c=z, cmap='viridis')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Value')
plt.title("3D Scatter Plot with Color Mapping")
plt