Python相关

27 minute read

Python 编程语言 系统学习大纲

一、 Python 语言概述

  • 1.1 Python 简介
    • 历史与发展:Guido van Rossum 创建,Python 2 和 Python 3
    • 设计哲学:简洁、易读、明确
    • 特点:解释型、动态类型、面向对象、跨平台
    • 应用领域:Web开发、数据分析、人工智能、自动化运维、科学计算
  • 1.2 Python 版本与生态系统
    • Python 2 与 Python 3 的主要区别
    • CPython、Jython、IronPython、PyPy 解释器
    • Python 包索引 (PyPI) 和 pip 包管理器
  • 1.3 开发环境搭建
    • 安装 Python 解释器
    • 配置环境变量
    • 使用 IDLE
    • 安装和使用 pip
    • 虚拟环境:venv、virtualenv、conda
    • 开发工具:PyCharm、VS Code、Jupyter Notebook

二、 基础语法

  • 2.1 第一个 Python 程序
    print("Hello, World!")
    
  • 2.2 变量与数据类型
    • 变量的定义与命名规则
    • 基本数据类型:
      • 数字类型:int、float、complex
      • 布尔类型:bool
      • 字符串类型:str
    • 类型检查与转换
  • 2.3 运算符
    • 算术运算符:+、-、*、/、//、%、**
    • 比较运算符:==、!=、>、<、>=、<=
    • 赋值运算符:=、+=、-= 等
    • 逻辑运算符:and、or、not
    • 位运算符:&、|、^、~、<<、>>
    • 成员运算符:in、not in
    • 身份运算符:is、is not
  • 2.4 输入与输出
    • 输入函数:input()
    • 输出函数:print()
    • 格式化输出:% 格式化、str.format()、f-string
      详情关于格式化输出

      一、格式化方法概览

      方法 Python版本 特点 示例
      %-格式化 所有版本 类似C语言printf,简单但功能有限 "Name: %s, Age: %d" % ("Alice", 25)
      str.format() 2.6+ 功能强大,支持位置、关键字、索引 "Name: {}, Age: {}".format("Alice", 25)
      f-string 3.6+ 语法简洁,性能好,推荐使用 f"Name: {name}, Age: {age}"
      Template字符串 所有版本 安全,适合用户输入 Template('Hello $name').substitute(name='Alice')

      二、%-格式化(旧式格式化)

      • 基本格式说明符

        格式符 说明 示例 输出
        %s 字符串 "%s" % "hello" hello
        %d 十进制整数 "%d" % 42 42
        %f 浮点数 "%.2f" % 3.14159 3.14
        %e 科学计数法 "%.2e" % 1234.5678 1.23e+03
        %x 十六进制整数 "%x" % 255 ff
        %o 八进制整数 "%o" % 64 100
        %% 百分号 "%.1f%%" % 99.5 99.5%
      • 格式化控制参数

        参数 含义 示例 输出
        宽度 最小字段宽度 "%10s" % "hello" (前面五个空格)hello
        精度 小数位数/最大字符数 "%.3f" % 3.14159 3.142
        对齐 -左对齐,默认右对齐 "%-10s" % "hello" hello(后面五个空格)
        填充 指定填充字符 "%010d" % 42 0000000042
        符号 +强制显示符号 "%+d" % 42 +42
        空格 正数前加空格 "% d" % 42 ` 42`

      三、str.format()方法

      • 基本语法对照表

        类型 语法 示例 输出
        位置参数 {} "{}, {}".format("A", "B") A, B
        索引参数 {0} "{1}, {0}".format("A", "B") B, A
        关键字参数 {key} "{name}, {age}".format(name="Alice", age=25) Alice, 25
        属性访问 {obj.attr} "{0.name}".format(person) Alice
        下标访问 {list[0]} "{0[0]}".format(lst) 1
      • 格式控制语法

          # 完整格式: {[索引/键]:[[填充]对齐][符号][#][0][宽度][,][.精度][类型]}
        
        控制项 语法 描述 示例 输出
        对齐 <, >, ^, = 左、右、居中、符号后填充 "{:>10}".format("test") (前面6个空格)test
        填充 任何字符 填充字符 "{:*^10}".format("test") ***test***
        符号 +, -, 空格 显示符号 "{:+}".format(42) +42
        宽度 数字 最小宽度 "{:5}".format(42) (前面三个空格)42
        精度 .数字 小数位数/字符数 "{:.2f}".format(3.14159) 3.14
        类型 s,d,f等 数据类型 "{:d}".format(42) 42
      • 类型说明符对照表

        类型符 含义 示例 输出
        s 字符串(默认) "{:s}".format("test") test
        d 十进制整数 "{:d}".format(42) 42
        b 二进制 "{:b}".format(10) 1010
        o 八进制 "{:o}".format(10) 12
        x 十六进制小写 "{:x}".format(255) ff
        X 十六进制大写 "{:X}".format(255) FF
        e 科学计数法小写 "{:.2e}".format(1000) 1.00e+03
        E 科学计数法大写 "{:.2E}".format(1000) 1.00E+03
        f 定点小数 "{:.2f}".format(3.14159) 3.14
        F 定点小数大写 "{:.2F}".format(float('inf')) INF
        g 通用格式 "{:g}".format(1000) 1000
        G 通用格式大写 "{:G}".format(1000) 1000
        % 百分比 "{:.1%}".format(0.85) 85.0%
        c 字符 "{:c}".format(65) A

      四、f-string(格式化字符串字面值)

      • 基本用法对比

        功能 f-string语法 等效的format()
        变量 f"{name}" "{}".format(name)
        表达式 f"{a + b}" "{}".format(a + b)
        函数调用 f"{name.upper()}" "{}".format(name.upper())
        条件表达式 f"{'偶数' if n%2==0 else '奇数'}" "{}".format('偶数' if n%2==0 else '奇数')
        字典键 f"{d['key']}" "{}".format(d['key'])
        列表索引 f"{lst[0]}" "{}".format(lst[0])
      • 格式控制示例

          # 对齐和宽度
          f"{'hello':<10}"   # 左对齐,宽度10
          f"{'hello':>10}"   # 右对齐,宽度10
          f"{'hello':^10}"   # 居中对齐,宽度10
          f"{'hello':*^10}"  # 居中,宽度10,用*填充
        
          # 数字格式化
          f"{3.14159:.2f}"   # 保留2位小数
          f"{1000:,.2f}"     # 千位分隔符
          f"{0.85:.1%}"      # 百分比
          f"{255:#x}"        # 带前缀的十六进制
        
      • 等号扩展(Python 3.8+)

          # 调试输出变量名和值
          x = 10
          y = 20
          print(f"{x=}, {y=}")  # 输出: x=10, y=20
          print(f"{x + y=}")    # 输出: x + y=30
        

      五、数字格式化特例

      • 千位分隔符对比

        方法 语法 示例输出
        %-格式化 "%,d" 不支持
        format() "{:,}" 1,000,000
        f-string f"{value:,}" 1,000,000
      • 不同进制输出

        进制 format() f-string
        二进制 "{:b}".format(10) f"{10:b}"
        八进制 "{:o}".format(10) f"{10:o}"
        十六进制 "{:x}".format(255) f"{255:x}"
        带前缀 "{:#x}".format(255) f"{255:#x}"

      六、格式化选项对比表

      功能需求 %-格式化 str.format() f-string
      简单替换 ✓ 简单 ✓ 较复杂 ✓ 最简单
      位置参数 ✓ 支持 ✓ 灵活 ✓ 支持
      关键字参数 ✗ 不支持 ✓ 支持 ✓ 支持
      表达式计算 ✗ 不支持 ✗ 不支持 ✓ 支持
      性能 一般 较慢 最快
      可读性 较差 一般 最好
      类型安全 较差 较好 最好
      调试支持 ✗ 不支持 ✗ 不支持 ✓ Python 3.8+

      七、高级格式化技巧

      • 日期时间格式化

          from datetime import datetime
          now = datetime.now()
        
          # 各种方法的日期格式化
          print("%Y-%m-%d %H:%M:%S" % (now.year, now.month, now.day, now.hour, now.minute, now.second))
          print("{:%Y-%m-%d %H:%M:%S}".format(now))
          print(f"{now:%Y-%m-%d %H:%M:%S}")
        
          # 常用日期格式符
          # %Y: 四位数年份 %y: 两位数年份
          # %m: 月份(01-12) %B: 月份全名
          # %d: 日(01-31) %A: 星期全名
        
      • 嵌套格式化

          # format() 嵌套
          width = 10
          precision = 2
          value = 12.3456
          print("{:{width}.{precision}f}".format(value, width=width, precision=precision))
        
          # f-string 嵌套
          print(f"{value:{width}.{precision}f}")
        
      • 自定义格式化

          class Person:
              def __init__(self, name, age):
                  self.name = name
                  self.age = age
                        
              def __format__(self, format_spec):
                  if format_spec == "long":
                      return f"Person(name={self.name}, age={self.age})"
                  elif format_spec == "short":
                      return f"{self.name}({self.age})"
                  else:
                      return str(self)
        
          p = Person("Alice", 25)
          print(f"{p:long}")   # Person(name=Alice, age=25)
          print(f"{p:short}")  # Alice(25)
        

      八、最佳实践建议

      场景 推荐方法 理由
      Python 3.6+ 新项目 f-string 语法简洁,性能好,可读性强
      需要兼容旧版本 str.format() 功能强大,兼容性好
      简单临时输出 print() 直接打印 快速调试
      用户输入模板 string.Template 安全性高,防止注入
      C语言背景开发者 %-格式化 熟悉度高,但建议迁移
      • 代码示例汇总
          # 各种方法的完整示例
          name = "Alice"
          age = 25
          height = 1.68
          salary = 50000.50
        
          # 1. %-格式化
          print("Name: %s, Age: %d, Height: %.2f" % (name, age, height))
        
          # 2. str.format()
          print("Name: {0}, Age: {1}, Salary: {2:,.2f}".format(name, age, salary))
          print("Name: {name}, Age: {age}, Salary: {salary:,.2f}".format(
              name=name, age=age, salary=salary))
        
          # 3. f-string (推荐)
          print(f"Name: {name}, Age: {age}, Salary: {salary:,.2f}")
          print(f"Name: {name:<10} Age: {age:>3} Height: {height:6.2f}m")
        
          # 4. 多行f-string
          message = (
              f"个人信息:\n"
              f"  姓名:{name}\n"
              f"  年龄:{age}\n"
              f"  身高:{height:.2f}m"
          )
        

      总结建议

      1. 优先使用f-string(Python 3.6+),语法最简洁,性能最好
      2. 需要兼容旧版本时使用str.format()
      3. 避免在新代码中使用%-格式化,除非维护旧代码
      4. 处理用户提供的模板时考虑string.Template以保证安全
      5. 复杂的格式化需求可结合多种方法使用
    • 文件输入输出基础

三、 流程控制

  • 3.1 条件语句
    if condition1:
        # 代码块1
    elif condition2:
        # 代码块2
    else:
        # 代码块3
    
  • 3.2 循环语句
    • while 循环
      while condition:
      # 循环体
      
    • for 循环
      for item in iterable:
      # 循环体
      
    • range() 函数
    • 循环控制语句:break、continue、pass
    • 循环的 else 子句
  • 3.3 异常处理
    • try、except、else、finally
      try:
      # 可能引发异常的代码
      except SomeException as e:
      # 异常处理
      else:
      # 无异常时执行
      finally:
      # 无论是否异常都执行
      
    • 常见内置异常类型
    • 抛出异常:raise
    • 自定义异常

四、 数据结构

  • 4.1 列表 (List)
    • 创建:[] 或 list()
    • 访问:索引、切片
    • 常用方法:append()、extend()、insert()、remove()、pop()、sort()、reverse()
    • 列表推导式
      [x**2 for x in range(10) if x % 2 == 0]
      
    详情关于列表

    一、列表创建与基本操作

    类别 方法/操作 描述 示例 结果
    创建列表 [] 创建空列表 lst = [] []
      list() 从可迭代对象创建 list('abc') ['a','b','c']
      列表推导式 快速生成列表 [x**2 for x in range(5)] [0,1,4,9,16]
    索引访问 lst[index] 访问指定位置元素 lst[0] 第一个元素
      lst[-1] 访问倒数第一个元素 lst[-1] 最后一个元素
    切片操作 lst[start:end] 获取子列表 lst[1:4] 索引1-3的元素
      lst[start:end:step] 带步长的切片 lst[::2] 每隔一个元素
      lst[::-1] 反转列表 lst[::-1] 反向列表
    修改元素 lst[index] = value 修改指定位置元素 lst[0] = 10 修改第一个元素
      切片赋值 修改子列表 lst[1:3] = [20,30] 替换1-2位置元素

    二、列表常用方法

    类别 方法 描述 示例 结果
    添加元素 append(x) 末尾添加元素 lst.append(4) [1,2,3,4]
      insert(i, x) 指定位置插入 lst.insert(1, 10) [1,10,2,3]
      extend(iterable) 合并列表 lst.extend([4,5]) [1,2,3,4,5]
    删除元素 remove(x) 删除第一个匹配元素 lst.remove(2) [1,3]
      pop([i]) 删除并返回指定位置元素 lst.pop(1) 返回2,列表变[1,3]
      clear() 清空列表 lst.clear() []
    查找元素 index(x) 返回元素索引 lst.index(2) 1
      count(x) 统计元素出现次数 lst.count(2) 1
      in 操作符 检查元素是否存在 2 in lst True
    排序操作 sort() 原地排序 lst.sort() 升序排列
      reverse() 原地反转 lst.reverse() 反转列表
      sorted() 返回排序后的新列表 sorted(lst) 新排序列表
      reversed() 返回反转迭代器 list(reversed(lst)) 新反转列表
    列表运算 + 列表连接 [1,2] + [3,4] [1,2,3,4]
      * 列表重复 [1,2] * 2 [1,2,1,2]
    列表复制 copy() 浅拷贝 lst.copy() 新列表对象
      list() 浅拷贝 list(lst) 新列表对象
      [:] 浅拷贝 lst[:] 新列表对象
    列表信息 len() 列表长度 len(lst) 元素个数
      max() 最大值 max(lst) 最大元素
      min() 最小值 min(lst) 最小元素
      sum() 元素求和 sum(lst) 所有元素和

    三、列表推导式与高级操作

    类别 语法 描述 示例 结果
    基本推导式 [expr for x in iterable] 对每个元素应用表达式 [x*2 for x in [1,2,3]] [2,4,6]
    带条件 [expr for x in iterable if cond] 筛选满足条件的元素 [x for x in range(5) if x%2==0] [0,2,4]
    嵌套循环 [expr for x in A for y in B] 嵌套循环 [(x,y) for x in [1,2] for y in [3,4]] [(1,3),(1,4),(2,3),(2,4)]
    条件表达式 [expr1 if cond else expr2 for x in iterable] 根据条件选择不同表达式 [x if x>0 else 0 for x in [-1,0,1]] [0,0,1]
    嵌套列表推导式 [[expr for y in iterable2] for x in iterable1] 创建嵌套列表 [[0 for _ in range(3)] for _ in range(2)] [[0,0,0],[0,0,0]]

    四、列表与迭代器

    类别 方法/函数 描述 示例 结果
    迭代 for循环 遍历列表 for x in lst: print(x) 依次输出每个元素
      enumerate() 同时获取索引和值 list(enumerate(['a','b'])) [(0,'a'),(1,'b')]
      zip() 并行迭代多个列表 list(zip([1,2],['a','b'])) [(1,'a'),(2,'b')]
    迭代器 iter() 获取迭代器 it = iter(lst) 列表迭代器
      next() 获取下一个元素 next(it) 第一个元素
    函数式编程 map() 对每个元素应用函数 list(map(str, [1,2,3])) ['1','2','3']
      filter() 筛选满足条件的元素 list(filter(lambda x:x>0, [-1,0,1])) [1]
      reduce() 累积计算 from functools import reduce; reduce(lambda x,y:x+y, [1,2,3]) 6

    五、列表性能与最佳实践

    建议 原因 好例子 坏例子
    使用append()添加元素 O(1)时间复杂度 lst.append(x) lst = lst + [x]
    使用列表推导式 简洁高效 [x**2 for x in range(10)] 手动循环创建列表
    使用in检查成员 清晰可读 if x in lst: 手动遍历检查
    避免在循环中修改列表 可能导致意外结果 创建新列表 在循环中删除元素
    使用切片复制列表 避免修改原列表 new = lst[:] new = lst(同一对象)
    排序时使用key参数 灵活指定排序规则 lst.sort(key=lambda x:x[1]) 手动实现排序逻辑
    使用collections.deque处理队列 高效的两端操作 from collections import deque 用列表实现队列(pop(0)效率低)

    六、常见问题与解决方案

    问题 解决方案 代码示例
    列表去重 使用set或字典 list(set(lst)) 或 list(dict.fromkeys(lst))
    展平嵌套列表 使用列表推导式 [item for sublist in lst for item in sublist]
    查找最大/最小元素索引 使用max/min的key参数 max_index = max(range(len(lst)), key=lst.__getitem__)
    按多个条件排序 使用sort的key参数返回元组 lst.sort(key=lambda x: (x[0], x[1]))
    分组操作 使用itertools.groupby from itertools import groupby; {k:list(v) for k,v in groupby(lst, key=func)}
    列表分块 使用切片 [lst[i:i+n] for i in range(0, len(lst), n)]
    合并多个列表 使用itertools.chain from itertools import chain; list(chain(list1, list2, list3))
    计算列表差异 使用集合运算 list(set(lst1) - set(lst2))

    七、性能注意事项

    操作 时间复杂度 说明
    索引访问 lst[i] O(1) 随机访问,常数时间
    追加元素 append() O(1) 平均情况,可能需要扩容
    插入元素 insert() O(n) 需要移动后续元素
    删除元素 remove()/pop(i) O(n) 需要移动元素
    成员检查 x in lst O(n) 需要遍历列表
    切片 lst[i:j] O(k) k是切片长度
    排序 sort() O(n log n) Timsort算法
    列表连接 lst1 + lst2 O(m+n) 创建新列表,复制所有元素

    八、实用代码片段

    # 1. 列表去重并保持顺序
    def unique_preserve_order(lst):
        seen = set()
        return [x for x in lst if not (x in seen or seen.add(x))]
    
    # 2. 展平嵌套列表
    def flatten(lst):
        return [item for sublist in lst for item in (sublist if isinstance(sublist, list) else [sublist])]
    
    # 3. 列表分块
    def chunk_list(lst, chunk_size):
        return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
    
    # 4. 查找出现次数最多的元素
    def most_common(lst):
        from collections import Counter
        return Counter(lst).most_common(1)[0][0]
    
    # 5. 列表元素频率统计
    def frequency_count(lst):
        freq = {}
        for item in lst:
            freq[item] = freq.get(item, 0) + 1
        return freq
    
    # 6. 合并多个列表
    def merge_lists(*lists):
        from itertools import chain
        return list(chain(*lists))
    
    # 7. 列表元素分组
    def group_by_key(lst, key_func):
        grouped = {}
        for item in lst:
            key = key_func(item)
            grouped.setdefault(key, []).append(item)
        return grouped
    

    九、最佳实践总结

    1. 选择合适的数据结构:列表适合有序、可重复的集合,需要快速随机访问
    2. 注意性能特征:了解常见操作的时间复杂度,避免在大列表上频繁使用O(n)操作
    3. 使用列表推导式:简洁高效,Pythonic风格
    4. 避免在循环中修改列表:如需修改,考虑创建新列表或使用倒序遍历
    5. 合理使用切片:复制、反转、获取子列表的利器
    6. 善用内置函数和方法:Python提供了丰富的列表操作方法
    7. 考虑使用其他数据结构:
      • 频繁插入/删除:考虑collections.deque
      • 快速成员检查:考虑set
      • 键值对:考虑dict

    Python列表是动态数组,支持任意类型的元素,是Python中最灵活、最常用的数据结构之一。掌握列表的操作和特性,是编写高效Python代码的基础。

  • 4.2 元组 (Tuple)
    • 创建:() 或 tuple()
    • 不可变性
    • 元组拆包
    详情关于元组

    一、元组基础

    • 什么是元组?
      • 不可变的有序序列
      • 一旦创建,不能修改、添加或删除元素
      • 用圆括号 () 表示
      • 支持任意类型的元素
    • 元组的特点

      特性 说明
      不可变性 创建后不能修改元素(但可包含可变元素)
      有序性 元素有固定顺序,可通过索引访问
      可哈希性 不可变元组可用作字典键
      内存效率 比列表占用更少内存
      性能优势 某些操作比列表更快

    二、元组创建

    # 创建空元组
    t1 = ()
    t2 = tuple()
    
    # 单元素元组(必须加逗号)
    t3 = (1,)
    t4 = 1,  # 括号可选,但推荐加括号
    
    # 多元素元组
    t5 = (1, 2, 3)
    t6 = 1, 2, 3  # 括号可选
    
    # 从可迭代对象创建
    t7 = tuple([1, 2, 3])  # 从列表
    t8 = tuple("abc")      # 从字符串 → ('a', 'b', 'c')
    

    三、元组基本操作

    • 访问元素
        t = (10, 20, 30, 40, 50)
      
        # 索引访问
        print(t[0])    # 10
        print(t[-1])   # 50 (倒数第一个)
      
        # 切片操作
        print(t[1:4])   # (20, 30, 40)
        print(t[::2])   # (10, 30, 50) 步长为2
        print(t[::-1])  # (50, 40, 30, 20, 10) 反转
      
    • 元组操作
        # 连接
        t1 = (1, 2)
        t2 = (3, 4)
        t3 = t1 + t2  # (1, 2, 3, 4)
      
        # 重复
        t4 = t1 * 3  # (1, 2, 1, 2, 1, 2)
      
        # 成员检查
        print(2 in t1)  # True
        print(5 not in t1)  # True
      
        # 长度
        print(len(t1))  # 2
      

    四、元组方法(只有2个)

    方法 描述 示例 结果
    count(x) 统计元素x出现次数 (1,2,2,3).count(2) 2
    index(x) 返回元素x首次出现的索引 (1,2,3,2).index(2) 1

    五、元组解包

    # 基本解包
    x, y, z = (1, 2, 3)
    print(x, y, z)  # 1 2 3
    
    # 星号解包
    a, *b, c = (1, 2, 3, 4, 5)
    print(a, b, c)  # 1 [2, 3, 4] 5
    
    # 交换变量
    x, y = 1, 2
    x, y = y, x
    print(x, y)  # 2 1
    
    # 函数返回多个值
    def get_stats(numbers):
        return min(numbers), max(numbers), sum(numbers)/len(numbers)
    
    minimum, maximum, average = get_stats([1, 2, 3, 4, 5])
    

    六、命名元组

    from collections import namedtuple
    
    # 定义命名元组类型
    Point = namedtuple('Point', ['x', 'y'])
    Color = namedtuple('Color', 'red green blue')  # 也可以传字符串
    
    # 创建实例
    p1 = Point(10, 20)
    p2 = Point(x=5, y=15)
    
    # 访问字段
    print(p1.x, p1.y)  # 10 20
    print(p1[0], p1[1])  # 10 20 (也可以用索引)
    
    # 命名元组方法
    print(Point._fields)  # ('x', 'y')
    print(p1._asdict())   # {'x': 10, 'y': 20}
    print(p1._replace(x=100))  # Point(x=100, y=20)
    

    七、元组 vs 列表

    对比项 元组 列表
    可变性 ❌ 不可变 ✅ 可变
    语法 圆括号 () 方括号 []
    性能 创建和访问更快 修改操作更多
    内存占用 较少 较多
    使用场景 数据记录、字典键 动态集合
    方法数量 2个 11+个
    哈希性 ✅ 可哈希 ❌ 不可哈希

    八、实用技巧

    1. 元组作为字典键
       # 元组可哈希,可作为字典键
       points = {
           (0, 0): "原点",
           (1, 0): "X轴上",
           (0, 1): "Y轴上"
       }
       print(points[(1, 0)])  # "X轴上"
      
    2. 元组包含可变对象
       # 元组不可变,但元素可以是可变对象
       t = ([1, 2], [3, 4])
       t[0].append(3)  # 可以修改元组中的列表
       print(t)  # ([1, 2, 3], [3, 4])
       # t[0] = [5, 6]  # 错误!不能替换整个元素
      
    3. 元组推导式
       # 元组推导式返回的是生成器
       gen = (x**2 for x in range(5))
       t = tuple(gen)  # 转为元组: (0, 1, 4, 9, 16)
      

    九、最佳实践

    • 何时使用元组:
      • 数据不应该被修改时
      • 用作字典键
      • 函数返回多个值
      • 保证数据安全
    • 何时使用列表:
      • 需要频繁修改数据
      • 需要排序、添加、删除等操作
      • 数据集合大小会变化
    • 性能考虑:
      • 元组创建和访问更快
      • 元组内存占用更小
      • 大量只读数据时用元组
    • 可读性:
      • 命名元组提高代码可读性
      • 元组解包使代码更简洁
      • 使用合适的命名表示数据含义

    十、常见误区

    1. 单元素元组必须加逗号:(1,) 不是 (1)
    2. 元组不可变:但可以包含可变对象
    3. 元组方法少:只有 count() 和 index()
    4. 元组推导式:实际返回生成器,需用 tuple() 转换
  • 4.3 集合 (Set)
    • 创建:{} 或 set()
    • 无序、不重复
    • 集合运算:并集、交集、差集、对称差集
    • 集合推导式
    详情关于集合

    一、集合基础

    • 什么是集合?
      • 无序的唯一元素集合
      • 用花括号 {} 表示,但空集合用 set()
      • 元素必须是可哈希的(不可变类型)
      • 支持数学集合运算
    • 集合的特点

      特性 说明
      无序性 元素没有固定顺序
      唯一性 自动去重,每个元素只出现一次
      可哈希性 元素必须是不可变类型
      高效查找 成员检查为 O(1) 时间复杂度
      可变性 集合本身可变,但元素必须不可变

    二、集合创建

    # 创建空集合(不能用 {},那是空字典)
    empty_set = set()
    
    # 从列表创建
    set1 = {1, 2, 3, 3, 2}  # 自动去重:{1, 2, 3}
    set2 = set([1, 2, 3, 4, 4])  # 从列表:{1, 2, 3, 4}
    
    # 从字符串创建(获取唯一字符)
    char_set = set("hello")  # {'h', 'e', 'l', 'o'}
    
    # 集合推导式
    square_set = {x**2 for x in range(5)}  # {0, 1, 4, 9, 16}
    

    三、集合基本操作

    • 增删元素
        s = {1, 2, 3}
      
        # 添加元素
        s.add(4)          # {1, 2, 3, 4}
        s.add(2)          # 已存在,不变
      
        # 添加多个元素
        s.update([5, 6, 7])  # {1, 2, 3, 4, 5, 6, 7}
        s.update({8, 9})     # 也可以从其他集合添加
      
        # 删除元素
        s.remove(3)       # 移除3,如果不存在则报错
        s.discard(10)     # 移除10,不存在也不报错
        s.pop()           # 随机移除一个元素并返回
        s.clear()         # 清空集合
      
    • 查询操作
        s = {1, 2, 3, 4, 5}
      
        # 成员检查
        print(3 in s)     # True
        print(6 not in s) # True
      
        # 长度
        print(len(s))     # 5
      
        # 遍历
        for item in s:
            print(item)   # 顺序不确定
      

    四、集合运算

    运算 方法 运算符 描述
    并集 union() | 所有元素
    交集 intersection() & 共同元素
    差集 difference() - 在A不在B的元素
    对称差集 symmetric_difference() ^ 只在一个集合中的元素
    子集检查 issubset() <= 是否为子集
    真子集检查 <   是否为真子集
    超集检查 issuperset() >= 是否为超集
    真超集检查 >   是否为真超集
    无交集检查 isdisjoint()   是否没有共同元素
    A = {1, 2, 3, 4}
    B = {3, 4, 5, 6}
    
    # 并集
    print(A | B)           # {1, 2, 3, 4, 5, 6}
    print(A.union(B))      # 同上
    
    # 交集
    print(A & B)           # {3, 4}
    print(A.intersection(B))  # 同上
    
    # 差集
    print(A - B)           # {1, 2} (在A中但不在B中)
    print(A.difference(B)) # 同上
    
    # 对称差集
    print(A ^ B)           # {1, 2, 5, 6} (只在其中一个集合中)
    print(A.symmetric_difference(B))  # 同上
    
    # 子集/超集检查
    C = {1, 2}
    print(C <= A)          # True (C是A的子集)
    print(A >= C)          # True (A是C的超集)
    print(C < A)           # True (C是A的真子集)
    print(A.isdisjoint({7, 8}))  # True (没有共同元素)
    

    五、不可变集合(frozenset)

    # 创建不可变集合
    fs = frozenset([1, 2, 3, 3, 2])  # frozenset({1, 2, 3})
    
    # 不可变集合操作
    fs2 = frozenset([2, 3, 4])
    print(fs & fs2)    # frozenset({2, 3}) 可进行集合运算
    # fs.add(4)        # 错误!不可变集合不能修改
    
    # 作为字典键
    dict_with_frozenset = {
        frozenset([1, 2]): "set1",
        frozenset([3, 4]): "set2"
    }
    

    六、集合常用方法

    方法 描述 示例
    copy() 返回浅拷贝 s2 = s1.copy()
    update() 添加多个元素 s.update([1,2,3])
    intersection_update() 原地交集 s.intersection_update(t)
    difference_update() 原地差集 s.difference_update(t)
    symmetric_difference_update() 原地对称差集 s.symmetric_difference_update(t)
    pop() 随机移除并返回一个元素 elem = s.pop()
    remove() 移除指定元素(不存在则报错) s.remove(1)
    discard() 移除指定元素(不存在不报错) s.discard(1)
    clear() 清空集合 s.clear()

    七、集合推导式

    # 基本集合推导式
    numbers = {x for x in range(10) if x % 2 == 0}  # {0, 2, 4, 6, 8}
    
    # 从字典创建(获取键的集合)
    data = {'a': 1, 'b': 2, 'c': 3}
    keys_set = {key for key in data}  # {'a', 'b', 'c'}
    
    # 复杂推导式
    pairs = {(x, y) for x in range(3) for y in range(3)}  # 9个坐标对
    

    八、集合与列表/元组转换

    # 列表去重(保持顺序)
    lst = [3, 1, 2, 1, 3, 2, 4]
    unique_ordered = list(dict.fromkeys(lst))  # [3, 1, 2, 4]
    
    # 列表去重(不关心顺序)
    unique_set = list(set(lst))  # 顺序可能变化
    
    # 检查列表是否有重复
    has_duplicates = len(lst) != len(set(lst))
    
    # 获取两个列表的共同元素
    list1 = [1, 2, 3, 4]
    list2 = [3, 4, 5, 6]
    common = set(list1) & set(list2)  # {3, 4}
    

    九、集合使用场景

    • 数据去重
        # 去除重复项
        emails = ["a@test.com", "b@test.com", "a@test.com", "c@test.com"]
        unique_emails = set(emails)  # 去重
      
    • 成员快速检查
        # 高效检查元素是否存在
        valid_users = {"alice", "bob", "charlie"}
        username = "alice"
        if username in valid_users:  # O(1)时间复杂度
            print("用户存在")
      
    • 数据对比
        # 比较两个数据集
        old_data = {1, 2, 3, 4, 5}
        new_data = {3, 4, 5, 6, 7}
      
        added = new_data - old_data    # {6, 7} 新增的
        removed = old_data - new_data  # {1, 2} 删除的
        common = old_data & new_data   # {3, 4, 5} 共同的
      

    十、性能比较

    操作 列表/元组 集合
    成员检查 (x in s) O(n) O(1)
    添加元素 O(1) (列表末尾) O(1)
    删除元素 O(n) O(1)
    遍历 O(n) O(n)
    交集/并集 O(n²) O(min(len(a), len(b)))

    十一、注意事项

    1. 元素必须可哈希:不能包含列表、字典等可变对象
    2. 集合推导式返回集合:{x for x in ...}
    3. 集合运算返回新集合:原始集合不变
    4. frozenset可用作字典键:普通集合不可以
    5. 集合顺序不确定:Python 3.7+ 中字典有序,但集合仍无序

    十二、实用代码片段

    # 1. 统计不同单词数量
    text = "hello world hello python world python programming"
    words = text.split()
    unique_words = len(set(words))  # 5
    
    # 2. 查找两个列表的不同元素
    list1 = [1, 2, 3, 4, 5]
    list2 = [4, 5, 6, 7, 8]
    only_in_list1 = set(list1) - set(list2)  # {1, 2, 3}
    only_in_list2 = set(list2) - set(list1)  # {6, 7, 8}
    
    # 3. 检查多个列表是否有共同元素
    lists = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]
    common_elements = set.intersection(*map(set, lists))  # 空集
    
    # 4. 获取列表中出现频率最高的元素
    from collections import Counter
    lst = [1, 2, 2, 3, 3, 3, 4]
    most_common = Counter(lst).most_common(1)[0][0]  # 3
    

    十三、最佳实践

    • 使用场景选择:
      • 需要快速成员检查 → 集合
      • 需要去重 → 集合
      • 需要集合运算 → 集合
      • 需要顺序或重复元素 → 列表
    • 性能优化:
      • 大量成员检查时,先将列表转为集合
      • 多次集合运算时,使用集合方法
      • 大型集合考虑内存占用
    • 代码可读性:
      • 使用集合运算符号(| & - ^)更简洁
      • 命名有意义,如 valid_users 而不是 s
      • 适当添加注释说明集合操作逻辑
  • 4.4 字典 (Dictionary)
    • 创建:{} 或 dict()
    • 键值对映射
    • 访问:dict[key]、dict.get()
    • 常用方法:keys()、values()、items()、update()、pop()
    • 字典推导式
      {x: x**2 for x in range(5)}
      
    详情关于字典

    一、字典基础

    • 什么是字典?
      • 键值对(key-value)的无序集合(Python 3.7+ 变为有序)
      • 键必须是不可变类型(字符串、数字、元组)
      • 值可以是任意类型
      • 用花括号 {} 表示,键值对用冒号 : 分隔
    • 字典的特点

      特性 说明
      键的唯一性 键不能重复,后出现的覆盖前面的
      可哈希键 键必须是不可变类型
      无序性 Python 3.6 前无序,3.7+ 保持插入顺序
      动态性 可动态添加、删除键值对
      高效查找 基于哈希表,查找速度为 O(1)

    二、字典创建

    # 创建空字典
    d1 = {}
    d2 = dict()
    
    # 直接创建
    d3 = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
    
    # 使用dict()构造函数
    d4 = dict(name='Bob', age=30)  # 关键字参数
    d5 = dict([('name', 'Charlie'), ('age', 35)])  # 可迭代对象
    d6 = dict(zip(['name', 'age'], ['David', 40]))  # zip函数
    
    # 字典推导式
    d7 = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}
    

    三、字典基本操作

    • 访问元素
        person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
      
        # 通过键访问
        print(person['name'])  # 'Alice'
      
        # 通过get()方法访问(推荐)
        print(person.get('age'))      # 25
        print(person.get('email'))    # None
        print(person.get('email', '未设置'))  # '未设置'(默认值)
      
        # 检查键是否存在
        if 'name' in person:
            print("键存在")
      
        # 获取所有键、值、键值对
        keys = person.keys()     # dict_keys(['name', 'age', 'city'])
        values = person.values() # dict_values(['Alice', 25, 'Beijing'])
        items = person.items()   # dict_items([('name','Alice'), ('age',25), ...])
      
    • 修改元素
        # 添加/修改键值对
        person['email'] = 'alice@example.com'  # 添加
        person['age'] = 26                     # 修改
      
        # 使用update()更新多个键值对
        person.update({'city': 'Shanghai', 'gender': 'female'})
      
        # 设置默认值
        person.setdefault('country', 'China')  # 如果不存在则设置
      
    • 删除元素
        # 删除指定键
        del person['city']
      
        # pop()删除并返回值
        age = person.pop('age')  # 返回25,从字典删除
        email = person.pop('email', '默认值')  # 提供默认值
      
        # popitem()删除最后一个键值对(Python 3.7+)
        key, value = person.popitem()  # 返回最后一个键值对
      
        # 清空字典
        person.clear()  # 清空所有键值对
      

    四、字典常用方法

    方法 描述 示例
    get(key[, default]) 安全获取值 d.get('key', 0)
    setdefault(key[, default]) 键不存在时设置默认值 d.setdefault('key', [])
    update([other]) 更新多个键值对 d.update({'a':1})
    pop(key[, default]) 删除并返回值 d.pop('key')
    popitem() 删除最后一个键值对 d.popitem()
    clear() 清空字典 d.clear()
    copy() 浅拷贝 d2 = d.copy()
    keys() 返回所有键 d.keys()
    values() 返回所有值 d.values()
    items() 返回所有键值对 d.items()
    fromkeys(seq[, value]) 从序列创建字典 dict.fromkeys(['a','b'], 0)

    五、字典遍历

    person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
    
    # 遍历键
    for key in person:
        print(key, person[key])
    
    # 遍历键值对
    for key, value in person.items():
        print(f"{key}: {value}")
    
    # 只遍历值
    for value in person.values():
        print(value)
    
    # 使用enumerate()获取索引
    for i, (key, value) in enumerate(person.items()):
        print(f"{i}. {key}={value}")
    

    六、字典推导式

    # 基本字典推导式
    squares = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}
    
    # 带条件的字典推导式
    even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
    
    # 键值交换
    original = {'a': 1, 'b': 2, 'c': 3}
    reversed_dict = {value: key for key, value in original.items()}
    
    # 合并两个列表为字典
    keys = ['a', 'b', 'c']
    values = [1, 2, 3]
    merged = {k: v for k, v in zip(keys, values)}  # {'a':1, 'b':2, 'c':3}
    

    七、嵌套字典

    # 创建嵌套字典
    students = {
        'Alice': {
            'age': 20,
            'grade': 'A',
            'courses': ['Math', 'Physics']
        },
        'Bob': {
            'age': 21,
            'grade': 'B',
            'courses': ['Chemistry', 'Biology']
        }
    }
    
    # 访问嵌套字典
    print(students['Alice']['age'])  # 20
    print(students.get('Bob', {}).get('grade', '未知'))  # 'B'
    
    # 修改嵌套字典
    students['Alice']['grade'] = 'A+'
    students['Alice']['courses'].append('English')
    
    # 遍历嵌套字典
    for name, info in students.items():
        print(f"姓名: {name}")
        for key, value in info.items():
            print(f"  {key}: {value}")
    

    八、特殊字典类型

    • 默认字典(defaultdict)
        from collections import defaultdict
      
        # 自动为不存在的键创建默认值
        word_count = defaultdict(int)  # 默认值为0
        for word in ["apple", "banana", "apple", "cherry"]:
            word_count[word] += 1
        # 结果: {'apple': 2, 'banana': 1, 'cherry': 1}
      
        # 默认值为列表
        group_by_letter = defaultdict(list)
        words = ["apple", "banana", "apricot", "cherry", "blueberry"]
        for word in words:
            group_by_letter[word[0]].append(word)
        # 结果: {'a':['apple','apricot'], 'b':['banana','blueberry'], 'c':['cherry']}
      
    • 有序字典(OrderedDict)
        from collections import OrderedDict
      
        # 保持插入顺序(Python 3.7+ 普通字典也有序,但OrderedDict有额外功能)
        ordered = OrderedDict()
        ordered['z'] = 1
        ordered['a'] = 2
        ordered['c'] = 3
        print(list(ordered.keys()))  # ['z', 'a', 'c'] 保持插入顺序
      
        # 移动到开头或结尾
        ordered.move_to_end('z')  # 将'z'移动到最后
        ordered.move_to_end('a', last=False)  # 将'a'移动到开头
      
    • 计数器(Counter)
        from collections import Counter
      
        # 统计元素出现次数
        words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
        word_count = Counter(words)
        print(word_count)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
      
        # 常见操作
        print(word_count.most_common(2))  # [('apple', 3), ('banana', 2)]
        print(word_count.total())  # 6 (总计数)
      
        # 合并计数器
        counter1 = Counter(['a', 'b', 'c', 'a'])
        counter2 = Counter(['a', 'b', 'd'])
        print(counter1 + counter2)  # Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
      

    九、字典与JSON

    import json
    
    # 字典转JSON字符串
    data = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
    json_str = json.dumps(data, ensure_ascii=False, indent=2)
    # 结果: 格式化的JSON字符串
    
    # JSON字符串转字典
    parsed_data = json.loads(json_str)
    # 结果: 恢复为字典
    
    # 字典与文件
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    with open('data.json', 'r', encoding='utf-8') as f:
        loaded_data = json.load(f)
    

    十、字典排序

    scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
    
    # 按键排序
    sorted_by_key = dict(sorted(scores.items()))
    # 结果: {'Alice':85, 'Bob':92, 'Charlie':78, 'David':95}(按字母顺序)
    
    # 按值排序(降序)
    sorted_by_value = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
    # 结果: {'David':95, 'Bob':92, 'Alice':85, 'Charlie':78}
    
    # 获取前N个最高分
    top_2 = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)[:2])
    # 结果: {'David':95, 'Bob':92}
    

    十一、字典合并

    dict1 = {'a': 1, 'b': 2}
    dict2 = {'b': 3, 'c': 4}
    dict3 = {'c': 5, 'd': 6}
    
    # 方法1: update()(修改原字典)
    merged1 = dict1.copy()
    merged1.update(dict2)  # dict1的'b'被dict2的'b'覆盖
    
    # 方法2: 字典解包(Python 3.5+)
    merged2 = {**dict1, **dict2, **dict3}
    # 后面的字典覆盖前面的相同键
    
    # 方法3: collections.ChainMap
    from collections import ChainMap
    chain = ChainMap(dict1, dict2, dict3)
    # 查询时按顺序查找,不创建新字典
    print(chain['b'])  # 2(来自dict1)
    
    # 方法4: 使用 | 运算符(Python 3.9+)
    merged3 = dict1 | dict2  # {'a':1, 'b':3, 'c':4}
    

    十二、实用代码片段

    # 1. 反转字典(值:键列表)
    original = {'a':1, 'b':2, 'c':1, 'd':3}
    reversed_dict = {}
    for key, value in original.items():
        reversed_dict.setdefault(value, []).append(key)
    # 结果: {1:['a','c'], 2:['b'], 3:['d']}
    
    # 2. 字典扁平化
    nested = {'a':{'b':1, 'c':2}, 'd':{'e':3, 'f':{'g':4}}}
    def flatten_dict(d, parent_key='', sep='.'):
        items = []
        for k, v in d.items():
            new_key = f"{parent_key}{sep}{k}" if parent_key else k
            if isinstance(v, dict):
                items.extend(flatten_dict(v, new_key, sep=sep).items())
            else:
                items.append((new_key, v))
        return dict(items)
    # 结果: {'a.b':1, 'a.c':2, 'd.e':3, 'd.f.g':4}
    
    # 3. 过滤字典
    data = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
    filtered = {k:v for k,v in data.items() if v > 2}  # {'c':3, 'd':4, 'e':5}
    
    # 4. 按多个条件排序字典列表
    students = [
        {'name':'Alice', 'score':85, 'age':20},
        {'name':'Bob', 'score':92, 'age':19},
        {'name':'Charlie', 'score':85, 'age':21}
    ]
    sorted_students = sorted(students, key=lambda x: (-x['score'], x['age']))
    # 按分数降序,年龄升序
    

    十三、性能与注意事项

    • 时间复杂度

      操作 平均时间复杂度 说明
      查找键 O(1) 基于哈希表
      插入键值对 O(1) 可能需要扩容
      删除键值对 O(1)  
      遍历 O(n) 遍历所有元素
    • 注意事项
      1. 键必须可哈希:不能使用列表、字典等可变对象作为键
      2. 字典无序:Python 3.6 前无序,3.7+ 保持插入顺序
      3. 内存使用:字典比列表占用更多内存
      4. 哈希冲突:当哈希冲突严重时,性能会下降
      5. 并发安全:字典不是线程安全的,多线程访问需要加锁
    • 最佳实践
      1. 使用 get() 方法安全访问
      2. 使用 setdefault() 设置默认值
      3. 使用字典推导式简化代码
      4. 大量数据时考虑使用 defaultdict 或 Counter
      5. 需要保持顺序时使用 OrderedDict(Python 3.7+ 普通字典也有序)

    十四、字典与其它数据结构转换

    # 字典 ↔ 列表
    data = {'a':1, 'b':2, 'c':3}
    keys_list = list(data.keys())      # ['a', 'b', 'c']
    values_list = list(data.values())  # [1, 2, 3]
    items_list = list(data.items())    # [('a',1), ('b',2), ('c',3)]
    
    # 列表 → 字典
    pairs = [('a',1), ('b',2), ('c',3)]
    dict_from_list = dict(pairs)  # {'a':1, 'b':2, 'c':3}
    
    # 两个列表 → 字典
    keys = ['a', 'b', 'c']
    values = [1, 2, 3]
    dict_from_two_lists = dict(zip(keys, values))  # {'a':1, 'b':2, 'c':3}
    
  • 4.5 字符串操作
    • 字符串方法:split()、join()、strip()、replace()、find()、startswith()、endswith()
    • 字符串格式化->详情见2.4-输入与输出
    • 原始字符串:r"string"
    详情关于python字符串

    一、字符串基础

    1. 字符串定义

       # 四种定义方式
       str1 = '单引号'
       str2 = "双引号"
       str3 = '''三引号可跨行
       这是第二行'''
       str4 = """双三引号也可跨行
       同样支持多行内容"""
      
       # 空字符串
       empty_str1 = ''
       empty_str2 = str()  # 使用构造函数
      
    2. 转义字符

      转义序列 含义 示例 输出
      \\ 反斜杠 "C:\\Users" C:\Users
      \' 单引号 'It\'s ok' It's ok
      \" 双引号 "He said: \"Hi\"" He said: "Hi"
      \n 换行 "Line1\nLine2" 两行文本
      \t 制表符 "Name\tAge" Name Age
      \r 回车 "Hello\rWorld" World
      \u Unicode字符 "\u4e2d" 中
    3. 原始字符串

       # 原始字符串(不转义)
       path1 = "C:\\Users\\Alice\\Documents"  # 需要转义
       path2 = r"C:\Users\Alice\Documents"    # 原始字符串,不需要转义
      
       # 正则表达式常用
       regex1 = "\\d+\\.\\d+"  # 匹配数字
       regex2 = r"\d+\.\d+"    # 更清晰的原始字符串
      

    二、字符串操作

    • 基本操作

        # 1. 拼接
        s1 = "Hello" + " " + "World"  # 字符串拼接
        s2 = "Hi" * 3                 # 重复: "HiHiHi"
      
        # 2. 索引访问
        text = "Python"
        print(text[0])    # P
        print(text[-1])   # n
        print(text[2:5])  # tho (切片)
      
        # 3. 长度
        length = len("Python")  # 6
      
    • 常用方法

        s = "  Hello World  "
      
        # 大小写转换
        print(s.upper())       # "  HELLO WORLD  "
        print(s.lower())       # "  hello world  "
        print(s.title())       # "  Hello World  "
        print(s.swapcase())    # "  hELLO wORLD  "
        print(s.capitalize())  # "  hello world  "
      
        # 空白处理
        print(s.strip())       # "Hello World"
        print(s.lstrip())      # "Hello World  "
        print(s.rstrip())      # "  Hello World"
      
        # 查找替换
        print(s.find("World"))     # 8
        print(s.rfind("o"))        # 8
        print(s.replace("World", "Python"))  # "  Hello Python  "
        print(s.count("l"))        # 3
      
        # 判断
        print("123".isdigit())     # True
        print("abc".isalpha())     # True
        print("abc123".isalnum())  # True
        print("  ".isspace())      # True
        print("Hello".startswith("He"))  # True
        print("World".endswith("ld"))    # True
      

    三、字符串格式化

    1. 三种格式化方式对比

       name, age = "Alice", 25
      
       # 1. % 格式化 (旧式)
       msg1 = "Name: %s, Age: %d" % (name, age)
      
       # 2. str.format() (Python 2.6+)
       msg2 = "Name: {}, Age: {}".format(name, age)
       msg3 = "Name: {0}, Age: {1}".format(name, age)
       msg4 = "Name: {n}, Age: {a}".format(n=name, a=age)
      
       # 3. f-string (Python 3.6+)
       msg5 = f"Name: {name}, Age: {age}"
       msg6 = f"Next year: {age + 1}"
       msg7 = f"Name: {name.upper()}"
      
    2. 格式规范

       # 数字格式化
       num = 123.45678
       print(f"{num:.2f}")      # 123.46
       print(f"{num:10.2f}")    # "    123.46"
       print(f"{num:010.2f}")   # "0000123.46"
      
       # 对齐
       text = "Python"
       print(f"|{text:<10}|")   # 左对齐: |Python    |
       print(f"|{text:^10}|")   # 居中对齐: |  Python  |
       print(f"|{text:>10}|")   # 右对齐: |    Python|
      
       # 千分位
       big_num = 1234567
       print(f"{big_num:,}")    # 1,234,567
      
       # 进制
       n = 255
       print(f"二进制: {n:b}")  # 11111111
       print(f"八进制: {n:o}")  # 377
       print(f"十六进制: {n:x}") # ff
       print(f"十六进制: {n:X}") # FF
      

    四、字符串编码

    • 编码基础

        # 字符串编码
        text = "你好,世界"
      
        # 编码为字节
        utf8_bytes = text.encode("utf-8")     # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
        gbk_bytes = text.encode("gbk")        # b'\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7'
      
        # 解码为字符串
        text1 = utf8_bytes.decode("utf-8")   # 你好,世界
        text2 = gbk_bytes.decode("gbk")      # 你好,世界
      
        # 常见编码
        encodings = ["utf-8", "gbk", "gb2312", "ascii", "latin-1", "utf-16"]
      
    • 处理编码问题

        # 处理编码错误
        text = "Python编程"
      
        try:
            # 尝试用错误的编码解码
            result = text.encode("utf-8").decode("ascii")
        except UnicodeDecodeError as e:
            print(f"解码错误: {e}")
      
        # 错误处理方式
        text.encode("utf-8").decode("ascii", errors="ignore")   # 忽略错误字符
        text.encode("utf-8").decode("ascii", errors="replace")  # 用?替换
        text.encode("utf-8").decode("ascii", errors="backslashreplace")  # 用\xhh替换
      
        # 检测编码
        import chardet
        data = "你好".encode("gbk")
        result = chardet.detect(data)  # {'encoding': 'GB2312', 'confidence': 0.99}
      

    五、字符串常量

    • 内置常量

        import string
      
        print(string.ascii_lowercase)   # 'abcdefghijklmnopqrstuvwxyz'
        print(string.ascii_uppercase)   # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        print(string.ascii_letters)     # 小写+大写
        print(string.digits)            # '0123456789'
        print(string.hexdigits)         # '0123456789abcdefABCDEF'
        print(string.octdigits)         # '01234567'
        print(string.punctuation)       # 标点符号: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
        print(string.whitespace)        # 空白字符: 空格、\t、\n、\r、\v、\f
        print(string.printable)         # 可打印字符
      

    六、字符串方法详解

    1. 判断方法

       s = "Python3"
      
       # 字符类型判断
       print(s.isalnum())     # True (字母或数字)
       print(s.isalpha())     # False (包含数字)
       print(s.isdecimal())   # False
       print(s.isdigit())     # False
       print(s.isnumeric())   # False
       print(s.islower())     # False
       print(s.isupper())     # False
       print(s.istitle())     # True (每个单词首字母大写)
       print(s.isspace())     # False
       print(s.isprintable()) # True
       print(s.isascii())     # True
      
       # 标识符判断
       print("var_name".isidentifier())  # True
       print("123var".isidentifier())    # False
      
    2. 变换方法

       s = "hello world"
      
       # 大小写变换
       print(s.capitalize())  # Hello world
       print(s.title())       # Hello World
       print(s.upper())       # HELLO WORLD
       print(s.lower())       # hello world
       print(s.swapcase())    # HELLO WORLD
      
       # 对齐
       print(s.ljust(20, "-"))  # hello world---------
       print(s.rjust(20, "-"))  # ---------hello world
       print(s.center(20, "-")) # ----hello world-----
      
       # 填充
       print("123".zfill(5))  # 00123
      

    七、字符串查找与替换

    • 查找方法

        text = "Python is great. Python is powerful."
      
        # 查找位置
        print(text.find("Python"))      # 0
        print(text.rfind("Python"))     # 18
        print(text.find("Java"))        # -1 (未找到)
        print(text.index("Python"))     # 0
        print(text.rindex("Python"))    # 18
        # print(text.index("Java"))     # ValueError
      
        # 计数
        print(text.count("Python"))     # 2
        print(text.count("is"))         # 2
        print(text.count("a"))          # 1
      
        # 检查
        print(text.startswith("Python"))  # True
        print(text.endswith("powerful.")) # True
      
    • 替换与分割

        text = "apple,banana,orange,grape"
      
        # 分割
        print(text.split(","))        # ['apple', 'banana', 'orange', 'grape']
        print(text.split(",", 2))     # ['apple', 'banana', 'orange,grape']
        print(text.rsplit(",", 2))    # ['apple,banana', 'orange', 'grape']
      
        # 行分割
        lines = "Line1\nLine2\r\nLine3"
        print(lines.splitlines())     # ['Line1', 'Line2', 'Line3']
        print(lines.splitlines(True)) # ['Line1\n', 'Line2\r\n', 'Line3']
      
        # 替换
        print(text.replace(",", ";"))  # apple;banana;orange;grape
        print(text.replace(",", ";", 2))  # apple;banana;orange,grape
      
        # 去除字符
        text2 = "***Hello***"
        print(text2.strip("*"))       # Hello
        print(text2.lstrip("*"))      # Hello***
        print(text2.rstrip("*"))      # ***Hello
      

    八、字符串模板

    from string import Template
    
    # 1. 安全替换
    template = Template("Hello, $name! Today is $day.")
    result = template.substitute(name="Alice", day="Monday")
    print(result)  # Hello, Alice! Today is Monday.
    
    # 2. 安全字典替换
    data = {"name": "Bob", "day": "Tuesday"}
    result2 = template.substitute(data)
    print(result2)  # Hello, Bob! Today is Tuesday.
    
    # 3. 安全替换(缺失键时不报错)
    result3 = template.safe_substitute(name="Charlie")
    print(result3)  # Hello, Charlie! Today is $day.
    
    # 4. 自定义分隔符
    class MyTemplate(Template):
        delimiter = "#"  # 使用#作为分隔符
    
    template2 = MyTemplate("Hello, #name!")
    print(template2.substitute(name="David"))  # Hello, David!
    

    九、性能考虑

    • 字符串连接效率

        import timeit
      
        # 1. 低效:循环中使用+
        def concat_plus(n):
            s = ""
            for i in range(n):
                s += str(i)
            return s
      
        # 2. 高效:使用列表推导
        def concat_join(n):
            return "".join(str(i) for i in range(n))
      
        # 3. 测试性能
        n = 10000
        time_plus = timeit.timeit(lambda: concat_plus(n), number=100)
        time_join = timeit.timeit(lambda: concat_join(n), number=100)
      
        print(f"+ 连接耗时: {time_plus:.4f}秒")
        print(f"join连接耗时: {time_join:.4f}秒")
      
        # 4. 格式化性能比较
        name, age = "Alice", 25
        time_format = timeit.timeit(lambda: "Name: {}, Age: {}".format(name, age), number=100000)
        time_fstring = timeit.timeit(lambda: f"Name: {name}, Age: {age}", number=100000)
      
        print(f"format耗时: {time_format:.4f}秒")
        print(f"f-string耗时: {time_fstring:.4f}秒")
      

    十、高级字符串处理

    1. 字符串与字节

       # 字符串与字节转换
       text = "Python编程"
       byte_data = text.encode("utf-8")
       print(type(byte_data))  # <class 'bytes'>
       print(byte_data)        # b'Python\xe7\xbc\x96\xe7\xa8\x8b'
      
       # bytes 和 bytearray
       b = b"hello"  # 不可变字节
       ba = bytearray(b"hello")  # 可变字节数组
       ba[0] = 72  # 修改第一个字节
       print(ba)  # bytearray(b'Hello')
      
       # 内存视图
       mv = memoryview(b"hello")
       print(mv[0])  # 104
       print(bytes(mv[:3]))  # b'hel'
      
    2. 正则表达式

       import re
      
       text = "Email: alice@example.com, Phone: 123-456-7890"
      
       # 查找
       emails = re.findall(r'\b[\w.-]+@[\w.-]+\.\w+\b', text)
       phones = re.findall(r'\b\d{3}-\d{3}-\d{4}\b', text)
       print(emails)  # ['alice@example.com']
       print(phones)  # ['123-456-7890']
      
       # 替换
       new_text = re.sub(r'\d{3}-\d{3}-\d{4}', 'XXX-XXX-XXXX', text)
       print(new_text)  # Email: alice@example.com, Phone: XXX-XXX-XXXX
      
       # 分割
       text2 = "apple, banana; orange, grape"
       items = re.split(r'[,\s;]+', text2)
       print(items)  # ['apple', 'banana', 'orange', 'grape']
      
       # 匹配对象
       match = re.search(r'(\w+)@([\w.]+)', text)
       if match:
           print(f"完整匹配: {match.group(0)}")  # alice@example.com
           print(f"用户名: {match.group(1)}")    # alice
           print(f"域名: {match.group(2)}")      # example.com
      

    十一、实用技巧

    • 常用模式
    # 1. 反转字符串
    s = "Python"
    reverse1 = s[::-1]  # 切片法
    reverse2 = ''.join(reversed(s))  # 内置函数
    print(reverse1, reverse2)  # nohtyP nohtyP
    
    # 2. 检查回文
    def is_palindrome(s):
        s = s.lower().replace(" ", "")
        return s == s[::-1]
    
    print(is_palindrome("A man a plan a canal Panama"))  # True
    
    # 3. 单词统计
    text = "Python is awesome. Python is powerful."
    words = text.split()
    word_count = {}
    for word in words:
        word = word.strip(".,!?").lower()
        word_count[word] = word_count.get(word, 0) + 1
    print(word_count)  # {'python': 2, 'is': 2, 'awesome': 1, 'powerful': 1}
    
    # 4. 提取数字
    import re
    text = "Price: $123.45, Weight: 12.5kg"
    numbers = re.findall(r'\d+\.?\d*', text)
    print(numbers)  # ['123.45', '12.5']
    
    # 5. 模板字符串
    from string import Template
    template = Template("Hello, $name! You have $count messages.")
    result = template.substitute(name="Alice", count=5)
    print(result)  # Hello, Alice! You have 5 messages.
    
    • 字符处理
    # 1. 字符映射转换
    trans_table = str.maketrans("aeiou", "12345")
    text = "hello world"
    print(text.translate(trans_table))  # h2ll4 w4rld
    
    # 2. 移除标点
    import string
    text = "Hello, World! How are you?"
    translator = str.maketrans("", "", string.punctuation)
    clean_text = text.translate(translator)
    print(clean_text)  # Hello World How are you
    
    # 3. 按长度排序单词
    sentence = "Python is a powerful programming language"
    words = sentence.split()
    words.sort(key=len, reverse=True)
    print(words)  # ['programming', 'powerful', 'language', 'Python', 'is', 'a']
    
    # 4. 生成随机字符串
    import random
    import string
    random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    print(random_str)  # 类似: 'X5j8K9mN2p'
    

    python字符串常用方法:

    类别 方法 描述 示例
    大小写 upper() 转大写 "hi".upper() → 'HI'
      lower() 转小写 "HI".lower() → 'hi'
      title() 单词首字母大写 "hello world".title() → 'Hello World'
    查找 find() 查找子串位置 "hello".find('l') → 2
      count() 统计出现次数 "hello".count('l') → 2
      startswith() 是否以指定开头 "file.txt".startswith('file') → True
      endswith() 是否以指定结尾 "file.txt".endswith('.txt') → True
    替换 replace() 替换子串 "hello".replace('l', 'x') → 'hexxo'
    分割 split() 分割字符串 "a,b,c".split(',') → ['a','b','c']
      join() 连接字符串 '-'.join(['a','b']) → 'a-b'
    修剪 strip() 去除两侧空白 " hi ".strip() → 'hi'
      lstrip()/rstrip() 去除左/右侧空白 " hi ".lstrip() → 'hi '
    检查 isdigit() 是否全数字 "123".isdigit() → True
      isalpha() 是否全字母 "abc".isalpha() → True
      isalnum() 是否字母或数字 "abc123".isalnum() → True

    关于各数据结构中查找元素的方法及对比

    数据结构 是否有序 是否可变 主要查找方法 时间复杂度
    列表(list) 有序 可变 index(), in, 切片 O(n)
    元组(tuple) 有序 不可变 index(), in, 切片 O(n)
    集合(set) 无序 可变 in O(1)平均
    字典(dict) 有序(3.7+) 可变 in(键), get(), 索引 O(1)平均
    字符串(str) 有序 不可变 find(), index(), in O(n)
    特性 find() index()
    返回结果 找到返回索引,否则-1 找到返回索引,否则抛出异常
    适用类型 字符串 字符串、列表、元组
    异常处理 不需要 需要try-except处理
    右向查找 有rfind() 有rindex()
    典型用法 检查是否存在并获取位置 确信元素存在时使用

五、 函数

  • 5.1 函数定义与调用
    def function_name(parameters):
        """文档字符串"""
        # 函数体
        return value
    
  • 5.2 参数传递
    • 位置参数
    • 关键字参数
    • 默认参数
    • 可变参数:*args
    • 关键字可变参数:**kwargs
  • 5.3 返回值
    • return 语句
    • 返回多个值
  • 5.4 变量作用域
    • 局部变量 vs 全局变量
    • global 关键字
    • nonlocal 关键字
  • 5.5 函数高级特性
    • 匿名函数:lambda
      lambda x, y: x + y
      
    • 高阶函数:map()、filter()、reduce()
    • 闭包
    • 装饰器
      def decorator(func):
      def wrapper(*args, **kwargs):
          # 装饰逻辑
          return func(*args, **kwargs)
      return wrapper
      
  • 5.6 生成器与迭代器
    • 迭代器协议:__iter__() 和 __next__()
    • 生成器:yield 关键字
    • 生成器表达式

python函数进阶:pyhon函数进阶

python常用内置函数:pyhon常用内置函数

六、 模块与包

  • 6.1 模块导入
    • import module
    • from module import name
    • import module as alias
    • 模块搜索路径
  • 6.2 模块编写
    • if __name__ == "__main__":
    • 模块文档字符串
  • 6.3 包结构
    • __init__.py 文件
    • 子包
    • 相对导入与绝对导入
  • 6.4 常用标准库模块
    • os:操作系统接口
    • sys:系统相关参数和函数
    • math:数学函数
    • random:生成随机数
    • datetime:日期和时间处理
    • json:JSON 编解码
    • re:正则表达式
    • collections:容器数据类型
    • itertools:迭代器工具
    • functools:高阶函数工具

七、 面向对象编程

  • 7.1 类与对象
    class MyClass:
        def __init__(self, param):
            self.param = param
            
        def method(self):
            return self.param
    
  • 7.2 属性与方法
    • 实例属性
    • 类属性
    • 实例方法
    • 类方法:@classmethod
    • 静态方法:@staticmethod
  • 7.3 继承
    class ChildClass(ParentClass):
        def __init__(self, param):
            super().__init__(param)
    
    • 单继承与多继承
    • 方法重写
    • super() 函数
  • 7.4 特殊方法
    • __init__():构造方法
    • __str__()、__repr__():字符串表示
    • __len__()、__getitem__()、__setitem__():容器方法
    • __eq__()、__lt__() 等:比较方法
    • __add__()、__mul__() 等:运算符重载
  • 7.5 属性访问控制
    • 公有属性
    • 私有属性:_ 和 __ 前缀
    • @property 装饰器
  • 7.6 高级主题
    • 抽象基类
    • 元类
    • 描述符
    • 混入类

八、 文件操作

  • 8.1 文件打开与关闭
    • open() 函数
    • 文件模式:'r'、'w'、'a'、'b'、'+'
    • close() 方法
    • with 语句
  • 8.2 文件读写
    • 读取:read()、readline()、readlines()
    • 写入:write()、writelines()
  • 8.3 文件指针操作
    • seek() 方法
    • tell() 方法
  • 8.4 文件与目录管理
    • os 模块:listdir()、mkdir()、remove()、rename()
    • os.path 模块:exists()、isdir()、isfile()、join()
    • shutil 模块:文件复制、移动、删除

九、 异常处理进阶

  • 9.1 异常层次结构
    • BaseException
    • Exception
    • 标准异常类
  • 9.2 自定义异常
    class MyException(Exception):
        def __init__(self, message):
            self.message = message
    
  • 9.3 异常链
    • raise ... from ...
  • 9.4 警告处理
    • warnings 模块

十、 并发编程

  • 10.1 多线程
    • threading 模块
    • 创建线程
    • 线程同步:Lock、RLock、Semaphore、Event、Condition
    • 线程间通信:Queue
  • 10.2 多进程
    • multiprocessing 模块
    • 创建进程
    • 进程间通信:Pipe、Queue、Manager
    • 进程池
  • 10.3 异步编程
    • asyncio 模块
    • async/await 语法
    • 协程
    • 异步IO操作

十一、 网络编程

  • 11.1 Socket 编程
    • socket 模块
    • TCP 客户端/服务器
    • UDP 客户端/服务器
  • 11.2 HTTP 编程
    • http.client 模块
    • urllib 模块
    • requests 第三方库
  • 11.3 Web 框架基础
    • Flask 简介
    • Django 简介
    • FastAPI 简介

十二、 数据库编程

  • 12.1 SQLite
    • sqlite3 模块
  • 12.2 MySQL
    • mysql-connector-python
    • pymysql
  • 12.3 PostgreSQL
    • psycopg2
  • 12.4 ORM
    • SQLAlchemy
    • Django ORM
  • 12.5 NoSQL
    • MongoDB:pymongo
    • Redis:redis

十三、 测试与调试

  • 13.1 调试工具
    • pdb 调试器
    • logging 模块
    • assert 语句
  • 13.2 单元测试
    • unittest 框架
    • pytest 框架
  • 13.3 性能分析
    • timeit 模块
    • cProfile 模块
    • line_profiler 第三方库

十四、 代码规范与工程化

  • 14.1 代码规范
    • PEP 8
    • 代码格式化工具:black、autopep8
    • 代码检查工具:pylint、flake8
  • 14.2 项目结构
    • 模块化设计
    • 包管理
    • 配置文件
  • 14.3 文档
    • 文档字符串
    • Sphinx 文档生成
  • 14.4 版本控制
    • Git 基础
    • GitHub/GitLab 使用
  • 14.5 打包与发布
    • setuptools
    • wheel
    • 发布到 PyPI

十五、 高级主题

  • 15.1 元编程
    • 装饰器高级用法
    • 元类
    • 描述符协议
  • 15.2 类型注解
    • 类型提示
    • typing 模块
    • mypy 静态类型检查
  • 15.3 并发模式
    • 生产者-消费者模式
    • 线程池/进程池模式
    • 异步模式
  • 15.4 内存管理
    • 引用计数
    • 垃圾回收
    • 内存分析工具
  • 15.5 C 扩展
    • Cython
    • ctypes
    • CFFI

十六、 应用领域

  • 16.1 Web 开发
    • Django/Flask/FastAPI
    • RESTful API
    • WebSocket
  • 16.2 数据分析
    • NumPy
    • pandas
    • Matplotlib
    • SciPy
  • 16.3 机器学习
    • scikit-learn
    • TensorFlow
    • PyTorch
  • 16.4 网络爬虫
    • Requests
    • BeautifulSoup
    • Scrapy
  • 16.5 自动化运维
    • 系统管理
    • 网络管理
    • 监控告警
  • 16.6 游戏开发
    • Pygame
    • PyOpenGL

十七、 学习资源

  • 17.1 官方文档
    • Python 官方文档
    • PEP 索引
  • 17.2 在线学习平台
    • Coursera
    • edX
    • 中国大学 MOOC
  • 17.3 书籍推荐
    • 入门:《Python编程:从入门到实践》
    • 进阶:《流畅的Python》
    • 算法:《Python算法教程》
  • 17.4 社区与论坛
    • Stack Overflow
    • GitHub
    • Python 中文社区
  • 17.5 实践项目
    • Web 应用开发
    • 数据分析项目
    • 自动化脚本编写
    • 开源项目贡献