前言
感谢 的 C++ 基础知识指南 提供的灵感来源。
不会开头怎么办。
前置知识
在正式开始之前,先来了解一些相关的概念。
Python 环境
解释器
Python 是一种解释型语言,代码通过解释器逐行执行。与编译型语言不同,Python 代码不需要预先编译成机器码。
CPython 是 Python 的官方实现,也是最常用的解释器。除此之外,还有 PyPy(注重性能)、Jython(运行在 JVM 上)、IronPython(运行在 .NET 上)等实现。洛谷支持 Python 与 PyPy。
虚拟环境
在开发 Python 项目时,不同项目可能依赖不同版本的包。虚拟环境(Virtual Environment)可以为每个项目创建独立的 Python 环境,避免依赖冲突。
常用工具:
venv:Python 3.3+ 内置的标准库virtualenv:第三方工具,功能更丰富conda:数据科学领域常用的环境管理工具
包管理
Python 的包管理主要通过 pip(Python Package Installer)进行。PyPI(Python Package Index)是官方的第三方库仓库,包含数十万个开源包。
Python 版本
Python 有两个主要版本系列:Python 2 和 Python 3。Python 2 已于 2020 年 1 月 1 日停止维护,最新版本为 Python 2.7。目前推荐使用 Python 3。
Python 3 的主要版本包括 3.5、3.6、3.7、3.8、3.9、3.10、3.11、3.12 等。截至本文发布,Python 3 最新正式版为 3.14,最新预览版为 3.15。每个新版本都会引入新特性和性能改进。
代码风格
Python 社区有公认的代码风格指南 PEP 8,它规定了变量命名、缩进、空格等细节。遵循统一的代码风格有助于提高代码可读性和团队协作效率。具体的风格见下文的 变量与作用域 - 变量命名。
基础语法
程序结构
# 单行注释
"""
多行注释
或文档字符串
"""
def main():
print("Hello, World!")
if __name__ == "__main__":
main()Python 使用缩进来表示代码块,通常使用 4 个空格。与 C++、Java 等语言不同,Python 没有大括号 {} 来界定代码块。
if __name__ == "__main__": 是一个常见的模式,用于判断当前模块是被直接运行还是被导入。这使得同一个 Python 文件既可以作为脚本直接执行,也可以作为模块被其他程序导入。
输入输出
Python 有多种输入输出方式:
# 基本输入输出
name = input("请输入你的名字: ")
print("你好!")
# 格式化字符串
age = 24
print("我今年 {} 岁".format(age)) # str.format()
print("我今年 %d 岁" % age) # % 格式化,较旧的方式
print(f"我今年 {age} 岁") # f-string,Python 3.6+
pi = 3.141592653589793238462643383279502884
print("{0:.6f}".format(ans)) # 保留6位小数
# 设置 end(结尾字符)、sep(间隔字符)
# 默认 end = '\n', sep = ' '
print(1, 1, 4, 5, 1, 4, end = '$', sep = '#') # 输出:1#1#4#5#1#4$
# 文件操作
with open("example.txt", "w") as f: # 使用 with 确保文件正确关闭
f.write("Hello, Python!\n")
with open("example.txt", "r") as f:
content = f.read()
print(content)Python 3 中,print 是一个函数而非语句,必须使用括号。input() 函数总是返回字符串,需要手动转换类型。
文件操作的最佳实践是使用 with 语句,它会自动管理资源,在代码块结束时关闭文件,即使发生异常也不会泄漏资源。
快速输入技巧
在洛谷算法题中,输入输出效率直接影响程序能否通过时间限制,尤其是处理大数据时需重点优化。
Python 标准 input() 速度较慢,处理万级以上数据时建议使用以下方法:
方法 1:导入 sys.stdin 快速读取
import sys
input = sys.stdin.read().split() # 一次性读取所有输入并分割为列表
ptr = 0
n = int(input[ptr])
ptr += 1
a = list(map(int, input[ptr:ptr+n]))
ptr += n方法 2:使用 sys.stdin.buffer 二进制读取
import sys
data = sys.stdin.buffer.read().decode()
input = data.split()
# 后续处理同上多行数据
在洛谷题目中,会涉及到多测而不给你测试数据组数的情况。这时,我们就又有多种方法处理。
方法 1:使用 input() 后判断异常抛出
try:
while True:
n = int(input()) # 每个测试数据内正常读入
s = input()
# ... 正常处理
except EOFError: # 捕获 End-Of-File,读入结束
pass方法 2:使用 sys.stdin.readlines()
import sys
lines = sys.stdin.readlines()
lines = [line.rstrip() for line in lines] # 去除末尾空白字符
for line in lines:
if not line.strip():
continue # 跳过空行
# line 是这一行的 str
n = int(line)
# 处理单组测试用例清空缓冲区
在交互题中,我们会需要清空缓冲区以达到交互的效果。
方法 1:使用 print() 中的参数 flush
print(end='', flush=True)方法 2:使用 sys.stdout.flush()
sys.stdout.flush()动态类型与鸭子类型
Python 是动态类型语言,变量不需要声明类型,类型在运行时确定:
x = 10 # int
x = "hello" # str
x = [1, 2, 3] # listPython 遵循“鸭子类型”原则:如果它走起来像鸭子,叫起来像鸭子,那么它就是鸭子。这意味着 Python 更关心对象的行为而非类型:
def quack(duck):
duck.quack() # 只要对象有 quack 方法,无论它是什么类型
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm quacking like a duck!")
quack(Duck()) # 输出: Quack!
quack(Person()) # 输出: I'm quacking like a duck!这种设计使得 Python 代码更加灵活,但也增加了运行时错误的风险。Python 3.5+ 引入了类型注解(Type Hints)来弥补这一缺陷,但类型检查只在静态分析时进行,不影响运行时行为。
变量与作用域
变量命名
Python 变量命名遵循以下规则:
- 只能包含字母、数字和下划线
- 不能以数字开头
- 区分大小写
- 不能使用关键字(如
if,for,while等)
命名约定(PEP 8):
- 普通变量和函数:
snake_case - 常量:
UPPER_CASE_WITH_UNDERSCORES - 类名:
PascalCase - 私有成员:
_single_leading_underscore(约定,非强制) - 特殊方法:
__double_leading_and_trailing_underscore__
这里 是原文。
作用域
Python 有四种作用域,按查找顺序为 LEGB 规则:
- Local:函数内部
- Enclosing:嵌套函数的外部函数
- Global:模块级别
- Built-in:内置名称
x = "global x" # 全局变量
def outer():
x = "outer x" # 外部函数变量
def inner():
x = "inner x" # 本地变量
print(x) # inner x
inner()
print(x) # outer x
outer()
print(x) # global x使用 global 和 nonlocal 关键字可以修改作用域:
x = "global"
def modify_global():
global x # 声明使用全局变量
x = "modified global"
def outer():
y = "outer"
def inner():
nonlocal y # 声明使用外部函数变量
y = "modified outer"
inner()
print(y) # modified outer变量赋值的陷阱
Python 中的变量赋值是引用赋值,对于可变对象需要特别小心:
# 问题:修改一个列表会影响另一个
list1 = [1, 2, 3]
list2 = list1 # list2 和 list1 指向同一个列表
list2.append(4)
print(list1) # [1, 2, 3, 4],意外被修改
# 解决方案:创建副本
list2 = list1.copy() # 浅拷贝
list2 = list(list1) # 也可以使用构造函数
list2 = list1[:] # 切片也是一种浅拷贝方式
# 对于嵌套结构,需要深拷贝
import copy
nested_list1 = [[1, 2], [3, 4]]
nested_list2 = copy.deepcopy(nested_list1)数据类型
基本类型
Python 有丰富的内置数据类型:
# 数字类型
int_num = 114514 # 整数
float_num = 1919.810 # 浮点数
complex_num = 114514 + 1919810j # 复数
# 布尔类型
is_true = True
is_false = False
# 字符串
s1 = 'single quotes'
s2 = "double quotes"
s3 = """triple quotes
can span multiple lines"""数字类型中,浮点数遵循 IEEE 754 标准。Python 3 中,除法运算符 / 总是返回浮点数,而 // 执行整数除法。
整数位数限制
这时候,有的同学就会问了,别人经常说 Python 自带高精度,你直接写输出 通过不了 P1932 A+B A-B A*B A/B A%B Problem 啊???
这时候,我们就要用下面这段代码解除整形位数限制。
import sys
sys.set_int_max_str_digits(0)或使用 Decimal 类。
序列类型
列表(List)
列表是 Python 最常用的数据结构,可变且有序:
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
input_list = list(map(int, input().split())) # 读入一整行并转换为整形列表
# 常用操作
fruits.append("orange") # 添加元素
fruits.insert(1, "grape") # 在指定位置插入
fruits.remove("banana") # 移除指定元素
popped = fruits.pop() # 移除并返回最后一个元素
fruits.sort() # 排序
fruits.reverse() # 反转
# 列表推导式(强大特性)
squares = [x**2 for x in range(10) if x % 2 == 0]
# 等价于
squares = []
for x in range(10):
if x % 2 == 0:
squares.append(x**2)元组(Tuple)
元组是不可变的序列,通常用于表示固定结构的数据:
# 创建元组
point = (3, 4)
person = ("John", 30, "Engineer")
# 解包
x, y = point
name, age, job = person
# 单元素元组需要逗号
single = (42,) # 不是单元素元组: (42)范围(Range)
range 是一个惰性序列,用于生成数字序列:
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(1, 10, 2): # 1, 3, 5, 7, 9
print(i)映射类型
字典(Dictionary)
字典是键值对的集合,使用哈希表实现,查找时间复杂度为 O(1):
# 创建字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 常用操作
person["email"] = "alice@example.com" # 添加/修改
age = person["age"] # 获取值
del person["city"] # 删除键值对
# 安全获取
phone = person.get("phone", "N/A") # 不存在时返回默认值
# 字典推导式
squares = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Python 3.9+ 合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # {"a": 1, "b": 3, "c": 4}集合类型
集合(Set)
集合是无序且不重复的元素集合,支持数学集合操作:
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 3, 4]) # {1, 2, 3, 4}
# 集合操作
fruits.add("orange")
fruits.remove("banana") # 不存在时抛出异常
fruits.discard("grape") # 不存在时不抛出异常
# 数学运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # 并集: {1, 2, 3, 4, 5, 6}
print(set1 & set2) # 交集: {3, 4}
print(set1 - set2) # 差集: {1, 2}
print(set1 ^ set2) # 对称差集: {1, 2, 5, 6}None 类型
None 是 Python 的空值,表示”无”或”空”:
result = None
def find_item(items, target):
for item in items:
if item == target:
return item
return None # 显式返回 None
print(find_item([1, 2, 3], 4)) # None控制结构
条件语句
x = 10
# 基本 if-elif-else
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
# 三元表达式
result = "偶数" if x % 2 == 0 else "奇数"
# 真值测试
empty_list = []
if not empty_list: # 空列表为 False
print("列表为空")
# 可以测试多种"假值"
# False, None, 0, 0.0, "", [], (), {}, set() 都为 False循环结构
# for 循环
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 带索引
for i, fruit in enumerate(fruits):
print(f"Index {i}: {fruit}")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 循环控制
for i in range(10):
if i == 3:
continue # 跳过当前迭代
if i == 7:
break # 退出循环
print(i)
else:
# 循环正常结束(没有 break)时执行
print("循环正常结束")异常处理
异常处理是 Python 的重要特性,用于处理运行时错误:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (TypeError, ValueError) as e:
print(f"类型或值错误: {e}")
except Exception as e: # 捕获所有异常(不推荐作为第一个except)
print(f"未知错误: {e}")
else:
# 没有异常时执行
print(f"结果: {result}")
finally:
# 无论是否发生异常都会执行
print("清理资源")最佳实践:
- 捕获特定异常而非通用
Exception - 使用
else子句处理无异常时的逻辑 - 使用
finally确保资源清理 - 不要使用异常控制正常流程
函数
基本定义与调用
def greet(name, greeting="Hello"):
"""打招呼函数
Args:
name: 人名
greeting: 问候语,默认为"Hello"
Returns:
问候字符串
"""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
print(greet(greeting="Hey", name="Charlie")) # Hey, Charlie!Python 函数支持:
- 默认参数值
- 关键字参数
- 文档字符串(推荐使用 Google 风格或 NumPy 风格)
- 返回多个值(实际返回元组)
可变参数
def sum_all(*args):
"""接受任意数量的位置参数"""
return sum(args)
def print_info(**kwargs):
"""接受任意数量的关键字参数"""
for key, value in kwargs.items():
print(f"{key}: {value}")
# 调用
print(sum_all(1, 2, 3, 4, 5)) # 15
print_info(name="Alice", age=30, city="New York")匿名函数
lambda 表达式用于创建小型匿名函数:
# 基本语法: lambda 参数: 表达式
square = lambda x: x**2
print(square(5)) # 25
# 常与高阶函数一起使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
even = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]高阶函数
Python 支持函数式编程范式,函数是一等公民:
def apply_operation(func, x, y):
"""接受函数作为参数"""
return func(x, y)
# 使用
add = lambda x, y: x + y
multiply = lambda x, y: x * y
print(apply_operation(add, 3, 4)) # 7
print(apply_operation(multiply, 3, 4)) # 12
# 内置高阶函数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
even = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
product = reduce(lambda x, y: x * y, numbers, 1) # 120 (需要从functools导入reduce)作用域与闭包
函数可以记住定义时的环境,形成闭包:
def make_multiplier(factor):
"""返回一个乘法函数"""
def multiplier(x):
return x * factor # 记住外部变量 factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15闭包在实现装饰器、回调函数等场景非常有用。
面向对象编程
类的基本定义
class Dog:
"""狗类"""
# 类属性(所有实例共享)
species = "Canis familiaris"
def __init__(self, name, age):
"""构造函数"""
# 实例属性
self.name = name
self.age = age
# 实例方法
def bark(self):
return f"{self.name} says Woof!"
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_good_boy():
return True
# 创建实例
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Buddy says Woof!
print(Dog.get_species()) # Canis familiaris
print(Dog.is_good_boy()) # TruePython 类支持:
- 实例属性与方法
- 类属性与类方法(
@classmethod) - 静态方法(
@staticmethod) - 特殊方法(如
__init__,__str__等)
继承与多态
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现 speak 方法")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# 多态
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())Python 支持多重继承,但需要谨慎使用:
class A:
def method(self):
print("A.method")
class B:
def method(self):
print("B.method")
class C(A, B): # C 继承自 A 和 B
pass
c = C()
c.method() # A.method(遵循方法解析顺序 MRO)
print(C.__mro__) # 显示方法解析顺序特殊方法(魔术方法)
Python 类可以通过实现特殊方法来自定义行为:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
"""重载 + 运算符"""
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
"""返回字符串表示"""
return f"Vector({self.x}, {self.y})"
def __len__(self):
"""返回"长度",用于 len() 函数"""
return 2
def __getitem__(self, index):
"""支持索引访问"""
if index == 0:
return self.x
elif index == 1:
return self.y
else:
raise IndexError("Vector index out of range")
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) # Vector(4, 6)
print(len(v3)) # 2
print(v3[0]) # 4常用特殊方法:
__init__:构造函数__str__:用户友好的字符串表示__repr__:开发者友好的字符串表示__eq__:相等比较__lt__,__le__,__gt__,__ge__:大小比较__add__,__sub__,__mul__,__truediv__:算术运算__getitem__,__setitem__,__delitem__:索引操作__len__:长度__iter__,__next__:迭代
迭代器与生成器
迭代器协议
Python 的迭代基于两个方法:__iter__() 和 __next__():
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
# 使用
for num in Counter(1, 5):
print(num) # 1, 2, 3, 4, 5生成器
生成器是创建迭代器的简单方式,使用 yield 关键字:
def fibonacci(n):
"""生成斐波那契数列"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 使用
for num in fibonacci(10):
print(num)
# 可以转换为列表
fib_list = list(fibonacci(10))生成器表达式类似于列表推导式,但使用圆括号,更加节省内存:
# 生成器表达式
squares = (x**2 for x in range(10))
for square in squares:
print(square)
# 比较列表推导式
squares_list = [x**2 for x in range(10)] # 立即计算并存储所有值生成器的高级用法
生成器可以接收值,实现双向通信:
def echo():
"""回显生成器"""
while True:
received = yield
print(f"收到: {received}")
# 使用
gen = echo()
next(gen) # 启动生成器
gen.send("Hello") # 收到: Hello
gen.send("World") # 收到: World生成器在处理大数据流、实现状态机、协程等场景非常有用。
装饰器
装饰器是 Python 的强大特性,允许修改或增强函数行为:
函数装饰器
def timer(func):
"""计时装饰器"""
import time
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 执行时间: {end_time - start_time:.4f} 秒")
return result
return wrapper
# 使用
@timer
def calculate_sum(n):
return sum(i for i in range(n))
result = calculate_sum(1000000)类装饰器
def singleton(cls):
"""单例模式装饰器"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
# 使用
@singleton
class DatabaseConnection:
def __init__(self):
print("初始化数据库连接")
# 两次调用返回同一个实例
conn1 = DatabaseConnection()
conn2 = DatabaseConnection()
print(conn1 is conn2) # True带参数的装饰器
def retry(max_attempts=3, delay=1):
"""重试装饰器"""
import time
def decorator(func):
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
if attempts == max_attempts:
raise
print(f"尝试 {attempts} 失败: {e}, {delay}秒后重试")
time.sleep(delay)
return None
return wrapper
return decorator
# 使用
@retry(max_attempts=5, delay=0.5)
def fetch_data(url):
# 模拟网络请求
import random
if random.random() < 0.7: # 70% 失败率
raise ConnectionError("网络连接失败")
return "数据成功获取"并发编程
多线程
Python 的 threading 模块支持多线程编程,但受 GIL(全局解释器锁)限制,CPU 密集型任务无法真正并行:
import threading
import time
def worker(name):
print(f"线程 {name} 开始")
time.sleep(2)
print(f"线程 {name} 结束")
# 创建线程
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(f"Thread-{i}",))
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
print("所有线程完成")多进程
对于 CPU 密集型任务,应使用 multiprocessing 模块,它绕过 GIL 限制:
import multiprocessing
import time
def cpu_bound_task(n):
"""CPU 密集型任务"""
return sum(i * i for i in range(n))
if __name__ == "__main__":
# 创建进程池
with multiprocessing.Pool(processes=4) as pool:
start_time = time.time()
# 异步执行多个任务
results = pool.map(cpu_bound_task, [10000000] * 4)
end_time = time.time()
print(f"结果: {results}")
print(f"执行时间: {end_time - start_time:.2f} 秒")异步IO
Python 3.5+ 支持异步IO,使用 async/await 语法,适合IO密集型应用:
import asyncio
import time
async def fetch_data(url):
"""模拟异步数据获取"""
print(f"开始获取 {url}")
await asyncio.sleep(1) # 模拟IO等待
print(f"完成获取 {url}")
return f"数据来自 {url}"
async def main():
start_time = time.time()
# 创建任务
tasks = [
fetch_data("https://api.example.com/data1"),
fetch_data("https://api.example.com/data2"),
fetch_data("https://api.example.com/data3"),
]
# 并发执行
results = await asyncio.gather(*tasks)
end_time = time.time()
print(f"结果: {results}")
print(f"执行时间: {end_time - start_time:.2f} 秒")
# 运行
asyncio.run(main())标准库精选
Python 标准库非常丰富,以下是几个常用模块:
collections 模块
提供替代内置容器的高性能数据结构:
from collections import defaultdict, Counter, namedtuple, deque
# defaultdict: 带默认值的字典
word_counts = defaultdict(int)
words = ["apple", "banana", "apple", "cherry"]
for word in words:
word_counts[word] += 1
# {'apple': 2, 'banana': 1, 'cherry': 1}
# Counter: 计数器
fruit_counts = Counter(["apple", "banana", "apple", "cherry"])
# Counter({'apple': 2, 'banana': 1, 'cherry': 1})
# namedtuple: 命名元组
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
# deque: 双端队列
d = deque([1, 2, 3])
d.append(4) # 右端添加
d.appendleft(0) # 左端添加
d.pop() # 右端移除
d.popleft() # 左端移除itertools 模块
提供创建迭代器的函数:
import itertools
# 无限迭代器
count = itertools.count(start=10, step=2) # 10, 12, 14, ...
cycle = itertools.cycle(["A", "B", "C"]) # A, B, C, A, B, C, ...
repeat = itertools.repeat("Hello", 3) # Hello, Hello, Hello
# 组合迭代器
numbers = [1, 2, 3]
perms = itertools.permutations(numbers, 2) # 排列: (1,2), (1,3), (2,1), (2,3), (3,1), (3,2)
combs = itertools.combinations(numbers, 2) # 组合: (1,2), (1,3), (2,3)
prods = itertools.product("AB", "12") # 笛卡尔积: ('A','1'), ('A','2'), ('B','1'), ('B','2')
# 有限迭代器
chain = itertools.chain([1, 2], [3, 4], [5]) # 1, 2, 3, 4, 5
takewhile = itertools.takewhile(lambda x: x < 5, [1, 4, 6, 4, 1]) # 1, 4
dropwhile = itertools.dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1]) # 6, 4, 1contextlib 模块
简化上下文管理器的创建:
from contextlib import contextmanager, suppress
# 自定义上下文管理器
@contextmanager
def open_file(filename, mode):
f = open(filename, mode)
try:
yield f
finally:
f.close()
# 使用
with open_file("example.txt", "w") as f:
f.write("Hello, context manager!")
# 忽略特定异常
with suppress(FileNotFoundError):
os.remove("nonexistent_file.txt")pathlib 模块
面向对象的文件系统路径操作(Python 3.4+):
from pathlib import Path
# 创建路径对象
current_dir = Path.cwd()
file_path = current_dir / "data" / "example.txt"
# 路径操作
print(file_path.exists()) # 检查文件是否存在
print(file_path.is_file()) # 检查是否为文件
print(file_path.parent) # 父目录
print(file_path.name) # 文件名
print(file_path.stem) # 无扩展名的文件名
print(file_path.suffix) # 扩展名
# 文件操作
if not file_path.parent.exists():
file_path.parent.mkdir(parents=True) # 创建目录
file_path.write_text("Hello, pathlib!") # 写入文本
content = file_path.read_text() # 读取文本
print(content)最佳实践
代码组织
- 使用模块和包组织代码
- 遵循单一职责原则
- 保持函数简短(通常不超过20行)
- 使用有意义的变量名
- 编写文档字符串
性能优化
- 优先使用内置函数和标准库
- 避免在循环内进行不必要的计算
- 使用生成器处理大数据
- 适当使用缓存
- 对性能关键部分使用 C 扩展或 Cython
错误处理
- 使用异常而非返回码
- 捕获特定异常
- 提供有意义的错误消息
- 使用上下文管理器确保资源清理
- 考虑使用断言验证内部逻辑
测试
- 使用 unittest 或 pytest 编写单元测试
- 遵循测试驱动开发(TDD)原则
- 覆盖边界条件和异常情况
- 使用 mock 测试外部依赖
结语
Python 是一门优雅而强大的语言,它的设计哲学强调代码可读性和简洁性。正如 Python 之禅(import this)所说:“优美胜于丑陋,明了胜于隐晦,简单胜于复杂。”
掌握这些知识,不会让你成为 Python 大师,但能让你写出更加优雅、高效的代码。Python 的魅力在于它的简洁与强大,希望这篇文章能帮助你更好地理解和使用这门语言。
正如 Guido van Rossum(Python 之父)所说:“代码阅读的频率远高于编写的频率。” 让我们共同努力,编写出既对机器友好,也对人类友好的代码。