data = ["2023-01-01", None, "2023-01-03"]
processed = format_dates(remove_null(data))
递归文件扫描
import os
def scan_dir(path, result=[]):
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isdir(full_path):
scan_dir(full_path, result) # 递归调用
else:
result.append(full_path)
return result
引言
本文将深入探讨相关技术要点,为读者提供实用的指导和建议。
最佳实践与技巧
- 参数设计原则
- 避免超过5个参数,使用字典或对象封装
- 默认参数必须为不可变对象
# 错误示例(默认可变对象)
def add_item(item, lst=[]):
lst.append(item)
return lst
# 正确方式
def add_item(item, lst=None):
lst = lst or []
lst.append(item)
return lst
- 类型提示增强可读性
from typing import List, Tuple
def process_data(data: List[Tuple[str, int]]) -> dict:
"""处理(姓名, 年龄)元组列表"""
return {name: age for name, age in data}
- Lambda函数的适用场景
# 简单操作替代完整函数
squares = list(map(lambda x: x**2, range(10)))
# 排序辅助
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
sorted_users = sorted(users, key=lambda u: u["age"])
常见问题与解决方案
问题1:变量意外修改
x = 10
def modify():
x += 1 # UnboundLocalError
# 解决方案:显式声明global
def correct_modify():
global x
x += 1
问题2:默认参数共享
def append_to(value, lst=[]):
lst.append(value)
return lst
print(append_to(1)) # [1]
print(append_to(2)) # [1,2] ! 非预期
# 解决方案:None代替并重建
def safe_append(value, lst=None):
lst = [] if lst is None else lst
lst.append(value)
return lst
问题3:递归深度限制
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
# n>1000时触发RecursionError
# 解决方案:迭代替代递归
def iter_factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
总结
Python函数作为代码复用的核心单元,其参数机制、作用域管理和设计模式深刻影响程序质量。关键要点包括:
- 严格区分位置参数/关键字参数的使用场景
- 警惕默认参数的可变性陷阱
- 合理选择递归与迭代的适用场景
- 类型提示显著提升代码可维护性
建议通过官方文档深入学习functools模块的partial、wraps等高级函数工具,进一步掌握装饰器和函数式编程技巧。函数设计能力直接反映开发者水平,值得持续钻研实践。
评论 (0)
暂无评论,快来抢沙发吧!