for、while、推导式入门 本文介绍 Python 的循环结构和列表推导式,是 Python 编程的核心技能。 1. for 循环 Python 的 for 循环用于遍历序列(列表、元组、字符串等)。 基本语法 # 遍历列表 fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit) # 遍历字符串 for char in "hello": print(char) # 遍历元组 colors = ("red", "green", "blue") for color in colors: print(color) range 函数 # range(start, stop, step) range(5) # 0,1,2,3,4 range(1, 6) # 1,2,3,4,5 range(0, 10, 2) # 0,2,4,6,8 range(5, 0, -1) # 5,4,3,2,1 # 常用场景 for i in range(10): print(i) # 打印 0-9 enumerate - 带索引遍历 fruits = ["apple", "banana", "orange"] # 带索引遍历 for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # 指定起始索引 for index, fruit in enumerate(fruits, start=1): print(f"{index}: {fruit}") zip - 并行遍历 names = ["Alice", "Bob", "Carol"] ages = [25, 30, 28] # 并行遍历 for name, age in zip(names, ages): print(f"{name}: {age}") # 多个序列 for name, age, city in zip(names, ages, ["Beijing", "Shanghai", "Guangzhou"]): print(f"{name}, {age}, {city}") 2. while 循环 while 循环在条件为真时重复执行代码块。 ...
pyproject.toml 现在该怎么理解
pyproject.toml 现在该怎么理解 pyproject.toml 是 Python 项目的现代配置文件,本文帮你理解它的作用和使用方法。 1. 什么是 pyproject.toml pyproject.toml 是 PEP 621 规定的项目配置文件,用于定义项目的元数据、构建系统和依赖。简单来说,它就是现代 Python 项目的「身份证」和「 строительства蓝图」。 2. 基本结构 [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta" [project] name = "mypackage" version = "1.0.0" description = "这是一个示例包" authors = [ {name = "张三", email = "zhangsan@example.com"} ] readme = "README.md" license = {text = "MIT"} requires-python = ">=3.8" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", ] dependencies = [ "requests>=2.28.0", "flask>=2.0.0", ] [project.optional-dependencies] dev = [ "pytest>=7.0.0", "black>=22.0.0", ] test = [ "pytest>=7.0.0", "pytest-cov>=4.0.0", ] [project.scripts] myapp = "mypackage.cli:main" [tool.setuptools] packages = ["mypackage"] [tool.pytest.ini_options] testpaths = ["tests"] python_files = ["test_*.py"] 3. 各部分详解 [build-system] 构建系统 这一部分定义了项目如何构建。requires 指定构建所需的工具版本,build-backend 指定使用哪个构建后端。 ...
Python 30 个实用技巧
Python 30 个实用技巧 本文整理 30 个 Python 开发中的实用技巧。 1. 交换变量 a, b = b, a 2. 多行字符串 text = """ 这是一段 多行文本 """ 3. 列表推导式 [x for x in range(10) if x % 2 == 0] 4. 集合去重 unique = list(set(duplicates)) 5. 三元运算 result = "正数" if x > 0 else "非正数" 6. 快速反转 reversed_list = list[::-1] 7. 字典合并 {**dict1, **dict2} 8. 列表转字符串 ",".join(list) 9. 链式比较 0 < x < 10 10. 计数器 from collections import Counter Counter(list) 11. 默认字典 from collections import defaultdict d = defaultdict(int) 12. 命名元组 from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) 13. 链式函数 # pipe 风格 ( x * 2 | str | len ) 14. 列表分块 [list[i:i+n] for i in range(0, len(list), n)] 15. 快速查找 any(x > 0 for x in list) all(x > 0 for x in list) 16. 展开嵌套列表 [item for sublist in list for item in sublist] 17. 获取索引 for i, v in enumerate(list): pass 18. 条件赋值 x = a if condition else b 19. 位运算判断奇偶 x % 2 == 0 # 或 x & 1 == 0 20. 快速创建列表 [0] * 10 # [0,0,0,...] 21. 解包赋值 a, *b, c = [1, 2, 3, 4, 5] # a=1, b=[2,3,4], c=5 22. 函数柯里化 def add(a): return lambda b: a + b 23. 延迟执行 lazy = lambda: expensive_func() 24. 滑动窗口 from itertools import islice def window(seq, n=2): it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result 25. 频率最高 Counter(list).most_common(1)[0] 26. 带默认值的 get dict.get(key, default) 27. zip 配对 dict(zip(keys, values)) 28. 字符串格式化 f"{name} is {age} years old" 29. 类型检查 isinstance(x, (int, float)) 30. 惰性求值 # 生成器表达式代替列表推导式 (x**2 for x in range(1000000)) 掌握这些技巧可以大大提高开发效率。
Python enumerate 与 range 技巧
Python enumerate 与 range 技巧 enumerate 和 range 是 Python 中最常用的迭代工具。 1. enumerate 基本用 fruits = ["apple", "banana", "orange"] for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 输出: # 0: apple # 1: banana # 2: orange 指定起始索引 for i, fruit in enumerate(fruits, start=1): print(f"{i}: {fruit}") # 输出: # 1: apple # 2: banana # 3: orange 2. range 技巧 # range(start, stop, step) range(5) # 0,1,2,3,4 range(1, 6) # 1,2,3,4,5 range(0, 10, 2) # 0,2,4,6,8 range(5, 0, -1) # 5,4,3,2,1 倒序遍历 for i in range(len(fruits) - 1, -1, -1): print(fruits[i]) 3. zip 并行迭代 names = ["Alice", "Bob"] ages = [25, 30] for name, age in zip(names, ages): print(f"{name}: {age}") 4. 组合使用 for i, (name, age) in enumerate(zip(names, ages)): print(f"{i}: {name}, {age}") 5. 实用示例 获取索引值对 def find_index(items, target): for i, item in enumerate(items): if item == target: return i return -1 enumerate 和 range 是 Python 编程的基础技能。
Python JSON 模块入门
Python JSON 模块入门 JSON 是常用的数据交换格式,Python 内置 json 模块支持编码和解码。 1. 基本操作 import json # Python 对象转 JSON 字符串 data = {"name": "Alice", "age": 25} json_str = json.dumps(data) print(json_str) # {"name": "Alice", "age": 25} # JSON 字符串转 Python 对象 parsed = json.loads(json_str) print(parsed) # {'name': 'Alice', 'age': 25} 2. 文件操作 # 写入 JSON 文件 with open("data.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) # 读取 JSON 文件 with open("data.json", "r", encoding="utf-8") as f: data = json.load(f) 3. 美化输出 data = {"name": "Alice", "skills": ["Python", "Go"]} # 缩进格式化 print(json.dumps(data, indent=2)) print(json.dumps(data, sort_keys=True)) # 按键排序 4. 处理日期 import json from datetime import datetime class DateEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj) data = {"time": datetime.now()} print(json.dumps(data, cls=DateEncoder)) 5. 处理自定义对象 def custom_decoder(d): return Person(d["name"], d["age"]) class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_dict(cls, d): return cls(d["name"], d["age"]) def to_dict(self): return {"name": self.name, "age": self.age} # 注册解析器 json.loads(json_str, object_hook=Person.from_dict) JSON 是 Web API 数据交换的核心格式。
Python lambda 函数
Python lambda 函数 lambda 是匿名函数,用于创建简单的函数对象。 1. 基本用法 # 普通函数 def add(a, b): return a + b # lambda 版本 add = lambda a, b: a + b 2. 常用场景 sort key points = [(1, 2), (3, 1), (2, 3)] points.sort(key=lambda x: x[1]) # 按 y 排序 map list(map(lambda x: x * 2, [1, 2, 3])) # [2, 4, 6] filter list(filter(lambda x: x > 0, [-1, 0, 1, 2])) # [1, 2] sorted sorted(data, key=lambda x: x["age"]) 3. 多参数 func = lambda x, y, z: x + y + z func(1, 2, 3) # 6 4. 条件表达式 max_func = lambda a, b: a if a > b else b abs_func = lambda x: -x if x < 0 else x lambda 简化了代码,但不宜过度使用。
Python map filter reduce
Python map filter reduce 这是函数式编程的三个核心函数。 1. map - 转换 # 对每个元素执行操作 numbers = [1, 2, 3, 4] # lambda result = list(map(lambda x: x * 2, numbers)) # [2, 4, 6, 8] # 多序列 a = [1, 2, 3] b = [4, 5, 6] list(map(lambda x, y: x + y, a, b)) # [5, 7, 9] 2. filter - 过滤 # 保留满足条件的元素 numbers = [1, 2, 3, 4, 5] result = list(filter(lambda x: x > 2, numbers)) # [3, 4, 5] 3. reduce - 聚合 from functools import reduce # 累积操作 numbers = [1, 2, 3, 4] result = reduce(lambda a, b: a + b, numbers) # 10 初始值 reduce(lambda a, b: a + b, numbers, 100) # 110 4. 组合使用 # 先过滤,再转换 result = list(map( lambda x: x * 2, filter(lambda x: x > 0, numbers) )) 5. functools 其他函数 from functools import partial # 固定部分参数 def power(base, exponent): return base ** exponent square = partial(power, exponent=2) square(5) # 25 map/filter/reduce 是函数式编程的基础。
Python 上下文管理器
Python 上下文管理器 上下文管理器用于管理资源,如文件、锁等。 1. with 语句 with open("file.txt") as f: content = f.read() # 自动关闭 2. 类实现 class MyContext: def __enter__(self): print("Enter") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Exit") return False with MyContext() as ctx: print("Inside") 3. 生成器实现 from contextlib import contextmanager @contextmanager def my_context(): print("Enter") try: yield finally: print("Exit") with my_context(): print("Inside") 4. 异常处理 class Context: def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is ValueError: print(f"Caught: {exc_val}") return True # 抑制异常 return False 5. closing from contextlib import closing class Resource: def close(self): print("Closing") with closing(Resource()) as res: print("Using") 上下文管理器让资源管理更安全。
Python 包管理工具 pipenv poetry
Python 包管理工具 pipenv poetry 现代 Python 项目推荐使用 pipenv 或 poetry 管理依赖。 1. pipenv 安装 pip install pipenv 常用命令 # 进入项目目录 cd myproject # 安装依赖 pipenv install # 安装开发依赖 pipenv install --dev pytest # 运行 pipenv run python main.py # 进入虚拟环境 pipenv shell Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] requests = "*" [dev-packages] pytest = "*" 2. poetry 安装 curl -sSL https://install.python-poetry.org | python3 - 常用命令 # 初始化 poetry new myproject # 添加依赖 poetry add requests poetry add pytest --group dev # 安装 poetry install # 运行脚本 poetry run python main.py # 进入 shell poetry shell pyproject.toml [tool.poetry] name = "myproject" version = "0.1.0" [tool.poetry.dependencies] python = "^3.8" requests = "^2.28" 3. 对比 特性 pipenv poetry 锁文件 Pipfile.lock poetry.lock 默认pip ✓ ✗ 构建 setuptools hatchling 两者都比 pip + requirements.txt 更现代。
Python 单元测试 unittest
Python 单元测试 unittest unittest 是 Python 标准库中的测试框架。 1. 基本结构 import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(1 + 1, 2) def test_divide(self): self.assertRaises(ZeroDivisionError, lambda: 1/0) if __name__ == '__main__': unittest.main() 2. 常用断言 self.assertEqual(a, b) self.assertNotEqual(a, b) self.assertTrue(x) self.assertFalse(x) self.assertIsNone(x) self.assertIsNotNone(x) self.assertIn(x, list) self.assertIsInstance(x, type) 3. setUp 和 tearDown class TestExample(unittest.TestCase): def setUp(self): self.data = load_test_data() def tearDown(self): clean_up(self.data) 4. 运行测试 python -m unittest python -m unittest test_module python -m unittest test_module.TestClass python -m unittest -v 5. pytest(更推荐) pip install pytest # 运行 pytest pytest -v pytest -k test_name 测试是保证代码质量的关键。