Python常用函数与语法大全

Python常用函数与语法大全

图片[1]-Python常用函数与语法大全 - 咸鱼科技躺盐社区-咸鱼科技躺盐社区
生成摘要
AI 生成,仅供参考

🌟 Python为何如此受欢迎?

print("人生苦短,我用Python!")  # 简洁优雅的语法
print("从网站开发到人工智能,无所不能!")  # 强大的功能
print("全球数百万开发者共同维护的生态圈")  # 活跃的社区

第一章:基石 · 语法内核与变量底层 📌

1.1 变量赋值与内存机制(不仅是“盒子”)

概念 详解 代码示例
动态类型 变量只是标签(引用),类型跟随对象 a = 10; a = "str" ✅
引用计数 sys.getrefcount(obj) 查看引用次数 import sys; a=[]; print(sys.getrefcount(a))
可变/不可变 不可变:int/str/tuple;可变:list/dict/set a=1; b=a; a=2 → b 仍为 1(int不可变)
小整数池 -5 ~ 256 预先缓存,地址相同 a=100; b=100; a is b → True
intern 机制 短字符串复用(含字母数字下划线) a="hello"; b="hello"; a is b → True(长字符串不一定)
# 深度理解可变默认参数(经典大坑 ⚠️)
def append_to_list(value, target=[]):
    target.append(value)
    return target

print(append_to_list(1))  # [1]
print(append_to_list(2))  # [1, 2]  —— 因为默认列表是同一个对象!

# ✅ 正确写法
def append_to_list(value, target=None):
    if target is None:
        target = []
    target.append(value)
    return target

1.2 运算符精讲

运算符 名称 进阶说明 示例
// 整除 向下取整(负向注意) -3 // 2 → -2(不是 -1)
% 取模 结果符号与除数相同 -3 % 2 → 1
** 幂运算 支持大数,效率高 pow(2, 10, 100) 取模幂(超大数优化)
:= 海象(Walrus) 赋值表达式(3.8+) while (line := fp.readline())
@ 矩阵乘法 用于 numpy 等 A @ B
is / is not 身份比较 比较内存地址(id()),别跟 == 混淆 [] is [] → False

第二章:数据结构 · 方法签名全展开 📚

2.1 字符串(str)—— 全方法分类

分类 方法 参数说明 返回值/作用
大小写 .upper().lower().swapcase().capitalize().title() 无 / 本地化变体 新字符串
查找定位 .find(sub).rfind().index().rindex().count() startend 可选 索引 / -1 或抛错
判断 .isalpha().isdigit().isalnum().isspace().isprintable() bool
填充对齐 .center(width, fillchar).ljust().rjust().zfill(width) 宽度+填充字符 新字符串
去除空白 .strip([chars]).lstrip().rstrip() 指定字符集(默认空格) 新字符串
分割合并 .split(sep, maxsplit).rsplit().partition(sep).join(iterable) 分隔符 / 最大切分次数 列表 / 字符串
替换翻译 .replace(old, new, count).translate(table) 配合 str.maketrans() 新字符串
格式化 .format(*args, **kwargs)f"{var=}" (3.8+) 位置/关键字 格式化后字符串
# 高级翻译:一次性替换多个字符 (`・ω・´)
trans = str.maketrans("abc", "123", "x")  # 第三个参数是删除字符集
print("a b c x".translate(trans))  # 输出: "1 2 3 "
 

2.2 列表(list)—— 作为栈与队列

方法 时间复杂度 说明 示例
.append(x) O(1) 尾部添加 lst.append(1)
.extend(iter) O(k) 批量追加 lst.extend([2,3])
.insert(i, x) O(n) 指定位置插入 lst.insert(0, 0)
.pop(i=-1) O(1)(尾部)/ O(n)(头部) 移除并返回 lst.pop()
.remove(x) O(n) 移除第一个匹配值 lst.remove(1)
.reverse() O(n) 原地反转 lst.reverse()
.sort(key=None, reverse=False) O(n log n) 原地排序(key 支持函数) lst.sort(key=lambda x: -x)
.copy() O(n) 浅拷贝(等价于 lst[:] new = lst.copy()

💡 切片赋值lst[1:3] = [10, 20](替换元素,长度可变)
💡 列表乘法[[]] * 3 大坑!会复制引用,导致内层列表联动。应使用列表推导 [[] for _ in range(3)]

2.3 字典(dict)—— 哈希表深度

方法 特性 3.9+ 新玩法
.get(key, default) 安全取值
.setdefault(key, default) 键不存在则设置
.update([other]) 合并更新 d1.update(d2)
合并运算符 d1 | d2 返回新字典(3.9+)
|= 原地合并 d1 |= d2 (3.9+)
.popitem() LIFO 弹出(3.7+ 保留插入顺序) 移除并返回最后插入的键值对
# 字典推导 + 计数 (◕‿◕)
text = "abracadabra"
char_count = {char: text.count(char) for char in set(text)}
# 更高效用 collections.Counter

2.4 集合(set)与不可变集合(frozenset

运算 符号 方法 说明
并集 | .union() 返回新集合
交集 & .intersection() 返回新集合
差集 - .difference() A – B (在A不在B)
对称差 ^ .symmetric_difference() 不同时存在的元素
子集/超集 <=>= .issubset().issuperset() 返回 bool

第三章:控制流 · 高级模式匹配(match-case) 🔀

Python 3.10 引入的 结构模式匹配(别当成简单的 switch!)

# 匹配字面量、变量、结构 (ノ◕ヮ◕)ノ
def process(command):
    match command.split():
        case ["quit"]:
            print("退出")
        case ["move", x, y] if int(x) > 0:  # 守卫(Guard)
            print(f"正向移动 {x}, {y}")
        case ["move", x, y]:
            print(f"移动 {x}, {y}")
        case [action, *rest]:  # 解包剩余部分
            print(f"未知动作: {action}, 参数: {rest}")
        case _:  # 通配符
            print("无效命令")

# 匹配类实例
class Point:
    __match_args__ = ("x", "y")
    def __init__(self, x, y): self.x = x; self.y = y

def where_is(point):
    match point:
        case Point(0, 0): print("原点")
        case Point(x, 0): print(f"X轴 {x}")
        case Point(0, y): print(f"Y轴 {y}")
        case Point(x, y) if x == y: print(f"对角线 {x}")
        case _: print("其他位置")

第四章:函数 · 从签名到装饰器工厂 🛠️

4.1 参数种类(必填、默认、可变、关键字独占)

 
参数类型 定义语法 调用方式
位置参数 def f(a, b) f(1, 2)
默认参数 def f(a, b=1) f(2)
可变位置 def f(*args) f(1,2,3) → args=(1,2,3)
可变关键字 def f(**kwargs) f(a=1) → kwargs={‘a’:1}
关键字独占(3.8+) def f(a, *, b) f(1, b=2) (b必须关键字传参)
位置独占(3.8+) def f(a, /, b) f(1, 2) (a不能关键字传参)
# 组合大法 (。◕‿◕。)
def complex_func(a, b, /, c, d, *args, e, f=10, **kwargs):
    # a, b 必须位置;c, d 位置或关键字;args 可变位置;e 必须关键字;f 默认关键字;kwargs 可变关键字
    pass

4.2 闭包与 nonlocal / global

def outer():
    count = 0
    def inner():
        nonlocal count  # 必须声明,否则视为局部变量
        count += 1
        return count
    return inner

counter = outer()
print(counter())  # 1
print(counter())  # 2

4.3 装饰器(带参数与类装饰器)

import functools
import time

# 带参数的装饰器 ( ̄▽ ̄)ノ
def retry(max_attempts=3, delay=1):
    def decorator(func):
        @functools.wraps(func)  # 保留原函数元数据!
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"第 {attempt} 次失败: {e}")
                    time.sleep(delay)
            return None
        return wrapper
    return decorator

@retry(max_attempts=5, delay=0.5)
def unstable_network_call():
    import random
    if random.random() < 0.7:
        raise ConnectionError("模拟失败")
    return "成功 🎉"

4.4 高阶函数:functools 精华

工具 作用 示例
functools.partial 固定部分参数 pow_of_2 = partial(pow, exp=2)
functools.cache / lru_cache 自动缓存结果(3.9+) @cache 装饰器
functools.singledispatch 单分派泛型函数 根据第一个参数类型重载
functools.reduce 累积操作 reduce(lambda x,y: x*y, [1,2,3]) → 6

第五章:迭代器 · 生成器 · 协程(yield 三部曲)🌀

概念 定义 特性
迭代器 实现 __iter__ 和 __next__ 惰性求值,只能遍历一次
生成器函数 含 yield 自动成为迭代器,保存状态
生成器表达式 (x**2 for x in range(10)) 比列表推导更省内存
协程(子生成器) yield from 委托给另一个生成器
# 无限序列生成器 (`・ω・´)
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
[next(fib) for _ in range(10)]  # [0,1,1,2,3,5,8,13,21,34]

# yield from 扁平化嵌套
def flatten(nested):
    for sub in nested:
        yield from sub  # 递归展开
print(list(flatten([[1,2], [3, [4,5]]])))  # 注意:只展一层,需递归处理多层级

第六章:内置函数 · 全分类大辞典(按功能分组)🗂️

6.1 数学与数值

函数 说明 坑点
abs(x) 绝对值 复数返回模
divmod(a, b) 返回 (商, 余数) 适用于大整数
round(x, ndigits) 四舍六入五成双(银行家舍入) round(2.5) → 2(不是3!)
pow(base, exp, mod=None) 取模幂 超大数取模极快

6.2 序列与迭代

函数 说明 进阶用法
enumerate(iter, start=0) 返回索引-值对 文件行号统计
zip(*iters, strict=False) 拉链打包 strict=True(3.10+)长度不一致时抛错
reversed(seq) 反向迭代器 必须是有序序列或实现 __reversed__
sorted(iter, key, reverse) 稳定排序 key 可指定多个属性(返回元组)

6.3 对象与属性(反射)

函数 说明 使用场景
dir([obj]) 查看属性列表 调试未知对象
getattr(obj, name, default) 获取属性 动态调用方法
setattr(obj, name, value) 设置属性 动态配置
hasattr(obj, name) 判断属性存在 防御性编程
callable(obj) 判断是否可调用 判断函数/类/方法

6.4 编译与执行(安全警告⚠️)

函数 说明 风险
eval(expr, globals, locals) 执行表达式 严重安全风险(不要用于用户输入)
exec(code, globals, locals) 执行代码块 同上
compile(src, file, mode) 编译为字节码 mode='eval' / 'exec' / 'single'

6.5 类型转换

函数 示例 注意
int(x, base) int('FF', 16) → 255 可转换字节/字符串
float(x) float('inf') 支持无穷大
complex(real, imag) 复数运算
bytes(s, encoding) 字符串转字节 必须指定编码
bytearray([source]) 可变字节序列 可原地修改

第七章:类与对象 · 元编程浅探 🏛️

7.1 魔法方法(双下划线)速查表

方法 触发时机 实现功能
__new__(cls, *args) 实例创建前(构造) 控制实例生成(单例模式)
__init__(self) 实例创建后(初始化) 属性赋值
__del__(self) 垃圾回收前 资源释放(不推荐依赖)
__str__(self) print(obj) / str(obj) 用户友好显示
__repr__(self) repr(obj) / 交互式 开发者友好显示(建议包含重建信息)
__call__(self, *args) obj() 使实例可调用(类似函数)
__getitem__(self, key) obj[key] 支持索引/切片
__setitem__(self, key, val) obj[key]=val 赋值
__iter__(self) for i in obj 返回迭代器
__next__(self) 迭代器取值 配合 __iter__
__enter__ / __exit__ with obj: 上下文管理器
__slots__ 类属性限定 节省内存,禁止动态添加属性
# 单例模式与 __new__ (。♥‿♥。)
class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# 上下文管理器手动实现
class ManagedFile:
    def __init__(self, name, mode):
        self.name = name; self.mode = mode
    def __enter__(self):
        self.file = open(self.name, self.mode)
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        if exc_type:
            print(f"异常被捕获: {exc_val}")
        return True  # 吞掉异常(慎用)

7.2 数据类(@dataclass)vs 传统类

from dataclasses import dataclass, field
from typing import List

@dataclass(order=True)  # 支持排序
class InventoryItem:
    name: str
    price: float = field(repr=True, compare=True)
    quantity: int = field(default=0, compare=False)
    tags: List[str] = field(default_factory=list)  # 避免可变默认值!

    def total_cost(self) -> float:
        return self.price * self.quantity
# 自动生成 __init__, __repr__, __eq__, __hash__ 等

第八章:异常 · 层级与自定义(最佳实践)🚨

8.1 内建异常层级(简略)

BaseException
├── SystemExitKeyboardInterrupt (应捕获 Exception 而非 BaseException)
├── Exception
│ ├── ArithmeticError (ZeroDivisionErrorOverflowError)
│ ├── LookupError (IndexErrorKeyError)
│ ├── TypeErrorValueErrorAttributeError
│ └── OSError (FileNotFoundError, PermissionError)

8.2 自定义异常与 raise from

class CustomAPIError(Exception):
    """自定义 API 错误基类"""
    def __init__(self, message, status_code=None):
        super().__init__(message)
        self.status_code = status_code

try:
    raise ConnectionError("连接超时")
except ConnectionError as e:
    # 链式异常,保留原始上下文  (╯°□°)╯
    raise CustomAPIError("请求失败") from e

 finally 中 return 会吞掉异常(极不推荐!)


第九章:文件与 I/O · 所有模式详解 📁

模式 说明 指针位置
'r' 只读(默认) 文件头
'w' 只写(清空) 文件头
'x' 排他性创建(文件存在则报错) 文件头
'a' 追加(写) 文件尾
'b' 二进制模式(需配合 rbwb
't' 文本模式(默认)
'+' 读写(r+w+a+ 视前缀而定
# 使用 seek 和 tell 操作指针 (`・ω・´)
with open('data.bin', 'rb+') as f:
    f.write(b'\x00\x01\x02')
    f.seek(1)          # 移动到索引1
    data = f.read(1)   # b'\x01'
    print(f.tell())    # 当前指针位置 -> 2

上下文管理器进阶:同时打开多个文件

from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(f'file_{i}.txt', 'w')) for i in range(3)]
    for f in files:
        f.write("批量管理 ✨")

第十章:类型提示(Type Hints)与 typing 深度 🧬

类型 用法 3.10+ 新写法
可选类型 Optional[int] int | None
联合类型 Union[int, str] int | str
列表 / 字典 List[int]Dict[str, int] list[int]dict[str, int]
元组 Tuple[int, str] tuple[int, str]
类型别名 type Point = tuple[float, float]
泛型 class Box(Generic[T]) 支持泛型约束
TypedDict 定义字典结构 用于 JSON 交互
Literal 限定字面量值 def f(mode: Literal['r', 'w'])
Callable 函数签名 Callable[[int, str], bool]
from typing import Protocol, runtime_checkable

# 鸭子类型 + 静态检查 (。◕‿◕。)
@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> None: ...

def render(obj: Drawable):
    obj.draw()
# 只要实现了 draw 方法的类,即使不继承,也能通过类型检查

第十一章:并发编程速览(多线程 / 异步)⚡

方式 适用场景 核心语法
多线程 (threading) I/O 密集型(GIL 限制 CPU) Thread(target=func).start()
多进程 (multiprocessing) CPU 密集型 Pool.map()
异步 (asyncio) 高并发 I/O(网络请求) async defawaitasyncio.run()
协程任务 并发执行任务 asyncio.gather(*tasks)
import asyncio

async def fetch_data(delay, name):
    print(f"开始 {name} (`・ω・´)")
    await asyncio.sleep(delay)  # 模拟IO
    print(f"完成 {name}")
    return f"结果 {name}"

async def main():
    # 并发执行
    results = await asyncio.gather(
        fetch_data(2, "A"),
        fetch_data(1, "B"),
        fetch_data(3, "C")
    )
    print(results)  # ['结果 A', '结果 B', '结果 C']

# asyncio.run(main())

第十二章:性能优化与调试技巧 🚀

12.1 性能测试

import timeit

# 测试列表推导 vs 循环
print(timeit.timeit('[x**2 for x in range(1000)]', number=10000))
print(timeit.timeit('for i in range(1000): lst.append(i**2)', setup='lst=[]', number=10000))

12.2 __slots__ 节省内存

class WithoutSlots:
    def __init__(self, name, age): self.name=name; self.age=age

class WithSlots:
    __slots__ = ('name', 'age')  # 禁止动态添加属性,大幅减少内存使用
    def __init__(self, name, age): self.name=name; self.age=age

12.3 字符串拼接(join 优于 +=

# ❌ 慢:每次 += 创建新对象
s = ""
for i in range(1000):
    s += str(i)

# ✅ 快
''.join(map(str, range(1000)))

12.4 调试工具

工具 用途 用法
pdb 命令行调试器 breakpoint() (3.7+)
sys.settrace 追踪代码执行 高级调试框架
cProfile 性能分析 python -m cProfile script.py
line_profiler 逐行耗时(第三方) @profile 装饰器

🔥 终章:3.10 ~ 3.12 新特性彩蛋

版本 特性 说明
3.10 match-case 结构化模式匹配
3.11 错误信息增强(ExceptionGroup 同时抛出多个异常 (except*)
3.11 大幅性能提升(CPython 3.11 比 3.10 快 10-60%)
3.12 更友好的类型提示(泛型语法简化) def f[T](x: T) -> T
3.12 f-string 更灵活(禁用 = 转义等) 复用引号等

🚀 Python学习路线图

  1. 基础语法 → 2. 数据结构 → 3. 函数编程

  2. 面向对象 → 5. 常用模块 → 6. 项目实践

# 你的第一个Python程序
print("✨ 恭喜完成Python入门! ✨")
print("接下来探索: ")
print(" - 网页开发(Django/Flask)") 
print(" - 数据分析(Pandas/Matplotlib)")
print(" - 人工智能(TensorFlow/PyTorch)")
print(" - 自动化脚本/爬虫")
 
 

💪 编程就像搭积木,每天进步一点点!
🐢 坚持练习比天赋更重要,动手写代码吧!
🎉 欢迎加入Python开发者的大家庭!

点我前往Python官网

 
© 版权声明
THE END
喜欢就支持一下吧
点赞15赞赏一下 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容