深度学习Python编程:从入门到工程实践

发布于:2025-03-25 ⋅ 阅读:(28) ⋅ 点赞:(0)

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

请添加图片描述

1.3 Python在工业界的应用场景

# 示例:使用FastAPI构建RESTful接口
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return {
   "item_name": item.name, "adjusted_price": item.price*1.1}

# 运行命令:uvicorn main:app --reload

1.4 Python版本选择指南

  • 性能对比测试
# 海象运算符示例(Python 3.8+)
if (n := len([1,2,3])) > 2:
    print(f"List length {
     n} is greater than 2")

第三章 Python核心语法精解

3.2 数据结构进阶操作

# 字典合并操作(Python 3.9+)
dict1 = {
   'a': 1, 'b': 2}
dict2 = {
   'b': 3, 'c': 4}
merged = dict1 | dict2  # {'a':1, 'b':3, 'c':4}

# 列表推导式优化
matrix = [[1,2], [3,4], [5,6]]
flatten = [num for row in matrix for num in row]  # [1,2,3,4,5,6]

3.4 上下文管理器原理

# 自定义上下文管理器
class DatabaseConnection:
    def __init__(self, db_name):
        self.db_name = db_name
        
    def __enter__(self):
        self.conn = sqlite3.connect(self.db_name)
        return self.conn
    
    def __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 调试器高级用法

# 使用pdb进行交互式调试
import pdb

def complex_calculation(a, b):
    result = 0
    for i in range(a):
        pdb.set_trace()  # 断点设置
        result += (i * b) ** 2
    return result

# 调试命令示例:
# n(ext), s(tep), c(ontinue), l(ist), p(rint)

第十章 数据分析与可视化

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 Axes3D

fig = 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