Python 语法迁移笔记 — Java工程师版
定位:从 Java 到 Python 的快速迁移速查手册 适用:有编程基础、需要快速上手 Python 工程开发的开发者 核心原则:对比理解,而非从零学习
一、核心差异总览 先建立整体认知,Python 与 Java 的本质差异:
维度
Java
Python
语言类型
静态类型,编译型
动态类型,解释型
语法风格
严格结构,大括号{}
缩进表示代码块
类型声明
String name = "Tom"
name = "Tom"(无声明)
语句结束
分号;
换行即结束
命名规范
camelCase
snake_case
入口方法
public static void main()
无强制入口,直接执行
空值
null
None
布尔值
true / false
True / False(首字母大写)
字符串
"" 不可变
"" 不可变,f"" 格式化
集合
List<T> 泛型
list 无泛型,元素类型随意
导入
import java.util.*
import os, from os import path
二、基础语法 2.1 变量与类型 Python 是动态类型,不需要声明类型 。但工程实践中必须写 Type Hints(FastAPI 强制依赖)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 name = "Alice" age = 25 height = 1.75 is_vip = True nothing = None name: str = "Alice" age: int = 25 height: float = 1.75 is_vip: bool = True result: None = None s = str (123 ) n = int ("456" ) f = float ("3.14" ) b = bool (1 )
Truthy / Falsy 规则 (判断条件时自动转换,比 Java 更宽松):
1 2 falsy = [0 , 0.0 , "" , [], {}, set (), None ]
2.2 字符串操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 s1 = '单引号' s2 = "双引号" s3 = '''多行 字符串''' name = "Tom" age = 25 print (f"姓名:{name} ,年龄:{age} ,明年:{age + 1 } " ) s = " Hello World " s.strip() s.lower() s.upper() s.startswith("He" ) s.find("World" ) s.replace("World" , "Python" ) s = "Python" s[0 ] s[-1 ] s[0 :3 ] s[2 :] s[:4 ] s[::2 ] s[::-1 ]
2.3 输入输出 1 2 3 4 5 6 7 8 9 10 11 12 print ("Hello" , "World" , sep="-" ) print ("第一行" , end="" ) name = input ("请输入姓名:" ) age = int (input ("请输入年龄:" ))
三、数据结构(核心中的核心) Python 的四大容器,列表和字典是使用频率最高的 。
3.1 列表 List(类比 Java ArrayList) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 arr = [1 , 2 , 3 , 4 , 5 ] mixed = [1 , "two" , 3.0 , True ] empty = [] arr[0 ] arr[-1 ] arr[0 ] = 100 arr.append(6 ) arr.insert(0 , 0 ) arr.extend([7 , 8 ]) arr.remove(100 ) popped = arr.pop() popped = arr.pop(0 ) if 3 in arr: print ("找到了" ) idx = arr.index(3 ) count = arr.count(3 ) arr = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] arr[2 :5 ] arr[:3 ] arr[5 :] arr[::2 ] arr[::-1 ] arr[:] arr.sort() arr.sort(reverse=True ) new_arr = sorted (arr) users = [("Tom" , 25 ), ("Jerry" , 20 ), ("Alice" , 30 )] users.sort(key=lambda x: x[1 ]) numbers = [1 , 2 , 3 , 4 , 5 ] squares = [] for n in numbers: squares.append(n * n) squares = [n * n for n in numbers] evens = [n for n in numbers if n % 2 == 0 ] pairs = [(x, y) for x in [1 , 2 ] for y in ['a' , 'b' ]]
3.2 字典 Dict(类比 Java HashMap,使用频率最高!) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 user = {"name" : "Tom" , "age" : 25 , "city" : "Beijing" } empty = {} empty = dict () user["name" ] user.get("name" ) user.get("gender" , "unknown" ) user["email" ] = "tom@example.com" del user["city" ] popped = user.pop("age" ) for key in user: print (key, user[key]) for key, value in user.items(): print (f"{key} : {value} " ) for value in user.values(): print (value) d1 = {"a" : 1 , "b" : 2 } d2 = {"b" : 3 , "c" : 4 } d3 = d1 | d2 d1 |= d2 numbers = [1 , 2 , 3 , 4 , 5 ] square_dict = {n: n * n for n in numbers} adults = {k: v for k, v in users.items() if v["age" ] >= 18 } from collections import defaultdictcounter = defaultdict(int ) counter["apple" ] += 1 groups = defaultdict(list ) groups["fruit" ].append("apple" )
3.3 元组 Tuple(不可变列表,类比不可变数组) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 t = (1 , 2 , 3 ) def get_user (): return "Tom" , 25 , "Beijing" name, age, city = get_user() locations = { (116.4 , 39.9 ): "北京" , (121.5 , 31.2 ): "上海" } wrong = (1 ) right = (1 ,) from collections import namedtupleUser = namedtuple("User" , ["name" , "age" , "city" ]) u = User("Tom" , 25 , "Beijing" ) print (u.name)
3.4 集合 Set(类比 Java HashSet) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 s = {1 , 2 , 3 , 3 , 3 } empty = set () a = {1 , 2 , 3 , 4 } b = {3 , 4 , 5 , 6 } a | b a & b a - b a ^ b items = [1 , 2 , 2 , 3 , 3 , 3 ] unique = list (set (items)) if 3 in s: pass
四、流程控制 4.1 条件判断 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 score = 85 if score >= 90 : grade = "A" elif score >= 80 : grade = "B" elif score >= 60 : grade = "C" else : grade = "D" grade = "及格" if score >= 60 else "不及格" if age >= 18 and age <= 60 and not is_vip: pass if not arr: pass if arr: pass if key in d: pass status = 200 match status: case 200 : print ("OK" ) case 404 : print ("Not Found" ) case 500 | 502 | 503 : print ("Server Error" ) case _: print ("Unknown" )
4.2 循环 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 for i in [1 , 2 , 3 ]: print (i) for i in range (5 ): print (i) for i in range (1 , 6 ): print (i) for i in range (0 , 10 , 2 ): print (i) arr = ["a" , "b" , "c" ] for idx, value in enumerate (arr): print (f"{idx} : {value} " ) for idx, value in enumerate (arr, 1 ): print (f"{idx} : {value} " ) names = ["Tom" , "Jerry" ] ages = [20 , 25 ] for name, age in zip (names, ages): print (f"{name} is {age} " ) count = 0 while count < 5 : count += 1 for n in range (10 ): if n == 3 : continue if n == 7 : break print (n) for n in range (5 ): if n == 10 : break else : print ("循环正常完成,没有找到10" ) for item in items: if item.is_valid(): break else : print ("没有有效元素" )
五、函数 5.1 定义与调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def greet (name: str ) -> str : """返回问候语(这是文档字符串 docstring)""" return f"Hello, {name} " def get_min_max (arr: list [int ] ) -> tuple [int , int ]: return min (arr), max (arr) minimum, maximum = get_min_max([3 , 1 , 4 , 1 , 5 ]) def connect (host: str = "localhost" , port: int = 3306 , timeout: int = 30 ) -> None : print (f"连接到 {host} :{port} ,超时:{timeout} s" ) connect() connect("192.168.1.1" ) connect(port=5432 ) connect("10.0.0.1" , timeout=10 ) def append_item (item, lst=[] ): lst.append(item) return lst append_item(1 ) append_item(2 ) def append_item (item, lst=None ): if lst is None : lst = [] lst.append(item) return lst
5.2 可变参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 def total (*numbers: int ) -> int : return sum (numbers) total(1 , 2 , 3 , 4 ) total() total(*[1 , 2 , 3 ]) def build_profile (**kwargs: str ) -> dict : return kwargs build_profile(name="Tom" , city="Beijing" ) data = {"name" : "Jerry" , "age" : "20" } build_profile(**data) def flexible (*args, **kwargs ): """接收任意参数""" print (f"位置参数:{args} " ) print (f"关键字参数:{kwargs} " ) flexible(1 , 2 , 3 , name="Tom" , age=25 ) def func (a, b, /, c, d, *args, e, f, **kwargs ): """ a, b —— 仅位置参数(/ 之前) c, d —— 位置或关键字 *args —— 接收多余位置参数 e, f —— 仅关键字参数(* 之后) **kwargs—— 接收多余关键字参数 """ pass
5.3 Lambda 表达式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 square = lambda x: x * x students = [("Tom" , 85 ), ("Jerry" , 72 ), ("Alice" , 91 )] students.sort(key=lambda s: s[1 ]) students.sort(key=lambda s: s[1 ], reverse=True ) scores = list (map (lambda s: s[1 ], students)) excellent = list (filter (lambda s: s[1 ] >= 90 , students)) scores = [s[1 ] for s in students] excellent = [s for s in students if s[1 ] >= 90 ]
5.4 装饰器(重点!FastAPI 的核心机制) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import functoolsimport timedef timing (func ): """计算函数执行时间的装饰器""" @functools.wraps(func ) def wrapper (*args, **kwargs ): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start print (f"{func.__name__} 耗时 {elapsed:.3 f} s" ) return result return wrapper @timing def slow_function (n: int ) -> int : """模拟耗时操作""" time.sleep(0.1 ) return n * n slow_function(5 ) def repeat (times: int ): def decorator (func ): @functools.wraps(func ) def wrapper (*args, **kwargs ): for _ in range (times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(times=3 ) def say_hello (): print ("Hello!" ) say_hello() @app.get("/users" ) def get_users (): ...def get_users (): ...get_users = app.get("/users" )(get_users)
六、面向对象 6.1 类定义 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class User : species = "Homo sapiens" def __init__ (self, name: str , age: int ) -> None : """构造方法(类比 Java 构造器)""" self .name = name self ._age = age self .__password = "" def greet (self ) -> str : return f"Hi, I'm {self.name} " @classmethod def from_birth_year (cls, name: str , year: int ) -> "User" : """类方法(类比 Java static 工厂方法)cls 类比 Java 的类名""" return cls(name, 2026 - year) @staticmethod def is_adult (age: int ) -> bool : """静态方法(无 self/cls,纯工具函数)""" return age >= 18 class Admin (User ): def __init__ (self, name: str , age: int , level: int ) -> None : super ().__init__(name, age) self .level = level def greet (self ) -> str : base = super ().greet() return f"{base} [Admin Lv.{self.level} ]" user = User("Tom" , 25 ) print (user.greet()) print (User.is_adult(20 )) admin = Admin("Boss" , 40 , 5 ) print (admin.greet())
6.2 魔术方法(Dunder Methods) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 class Vector : """二维向量,演示常见魔术方法""" def __init__ (self, x: float , y: float ) -> None : self .x = x self .y = y def __str__ (self ) -> str : return f"Vector({self.x} , {self.y} )" def __repr__ (self ) -> str : return f"Vector({self.x!r} , {self.y!r} )" def __eq__ (self, other: object ) -> bool : if not isinstance (other, Vector): return NotImplemented return self .x == other.x and self .y == other.y def __add__ (self, other: "Vector" ) -> "Vector" : return Vector(self .x + other.x, self .y + other.y) def __sub__ (self, other: "Vector" ) -> "Vector" : return Vector(self .x - other.x, self .y - other.y) def __len__ (self ) -> int : return 2 def __call__ (self, scale: float ) -> "Vector" : """让实例像函数一样被调用""" return Vector(self .x * scale, self .y * scale) v1 = Vector(1 , 2 ) v2 = Vector(3 , 4 ) print (v1 + v2) print (v1 == Vector(1 , 2 )) print (v1(2 ))
6.3 Dataclass(Python 3.7+,工程强烈推荐) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from dataclasses import dataclass, fieldfrom typing import List @dataclass class User : name: str age: int email: str = "" tags: List [str ] = field(default_factory=list ) user = User("Tom" , 25 , "tom@example.com" ) print (user) @dataclass(frozen=True ) class Point : x: float y: float
七、文件 IO 与异常处理 7.1 文件操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 with open ("data.txt" , "r" , encoding="utf-8" ) as f: content = f.read() with open ("data.txt" , "r" , encoding="utf-8" ) as f: for line in f: print (line.strip()) with open ("output.txt" , "w" , encoding="utf-8" ) as f: f.write("第一行\n" ) f.write("第二行\n" ) f.writelines(["第三行\n" , "第四行\n" ]) with open ("log.txt" , "a" , encoding="utf-8" ) as f: f.write("新增日志\n" ) import jsondata = {"name" : "Tom" , "age" : 25 , "tags" : ["AI" , "Python" ]} with open ("user.json" , "w" , encoding="utf-8" ) as f: json.dump(data, f, ensure_ascii=False , indent=2 ) with open ("user.json" , "r" , encoding="utf-8" ) as f: loaded = json.load(f) json_str = json.dumps(data, ensure_ascii=False ) parsed = json.loads(json_str) import csvwith open ("data.csv" , "w" , newline="" , encoding="utf-8" ) as f: writer = csv.writer(f) writer.writerow(["name" , "age" , "city" ]) writer.writerows([ ["Tom" , 25 , "Beijing" ], ["Jerry" , 20 , "Shanghai" ] ]) with open ("data.csv" , "r" , encoding="utf-8" ) as f: reader = csv.DictReader(f) for row in reader: print (row["name" ], row["age" ])
7.2 异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 try : result = 10 / 0 except ZeroDivisionError as e: print (f"除零错误: {e} " ) except Exception as e: print (f"其他错误: {e} " ) else : print (f"结果: {result} " ) finally : print ("无论如何都会执行" ) class ValidationError (Exception ): """参数校验失败""" pass def validate_age (age: int ) -> None : if age < 0 or age > 150 : raise ValidationError(f"年龄 {age} 不合法" ) manager = open ("file.txt" , "r" ) enter_result = manager.__enter__() try : pass finally : manager.__exit__(None , None , None ) from contextlib import contextmanager@contextmanager def managed_resource (name: str ): print (f"获取资源:{name} " ) resource = {"name" : name} try : yield resource finally : print (f"释放资源:{name} " ) with managed_resource("db_connection" ) as conn: print (f"使用资源:{conn} " )
八、进阶特性 8.1 生成器 Generator(流式处理的核心) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 def count_up_to (n: int ): """生成 1 到 n 的数字,惰性求值""" i = 1 while i <= n: yield i i += 1 for num in count_up_to(5 ): print (num) squares_list = [x * x for x in range (1000000 )] squares_gen = (x * x for x in range (1000000 )) def read_large_file (filepath: str ): """逐行读取大文件,内存友好""" with open (filepath, "r" , encoding="utf-8" ) as f: for line in f: yield line.strip() for line in read_large_file("huge.log" ): if "ERROR" in line: print (line) def flatten (nested ): """展平嵌套列表""" for item in nested: if isinstance (item, list ): yield from flatten(item) else : yield item list (flatten([1 , [2 , [3 , 4 ]], 5 ]))
8.2 迭代器协议 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class CountDown : def __init__ (self, start: int ) -> None : self .start = start def __iter__ (self ): return self def __next__ (self ): if self .start <= 0 : raise StopIteration self .start -= 1 return self .start + 1 for n in CountDown(5 ): print (n) def countdown (start: int ): while start > 0 : yield start start -= 1
九、Type Hints 详解(FastAPI 的基础) 9.1 基础类型标注 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from typing import Optional , Union , List , Dict , Tuple , Set , Any , Callable name: str = "Tom" count: int = 0 price: float = 9.99 flag: bool = True anything: Any = "任意类型" def find_user (user_id: int ) -> Optional [dict ]: return None def parse_value (value: str ) -> Union [int , float , str ]: pass def parse_value (value: str ) -> int | float | str : pass names: List [str ] = ["Tom" , "Jerry" ] scores: Dict [str , int ] = {"Tom" : 85 , "Jerry" : 90 } point: Tuple [int , int ] = (10 , 20 ) tags: Set [str ] = {"AI" , "Python" } handler: Callable [[int , str ], bool ] JsonDict = Dict [str , Any ] UserData = Dict [str , Union [str , int ]] def process (data: JsonDict ) -> UserData: pass
9.2 泛型与自定义类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 from typing import TypeVar, Generic T = TypeVar("T" ) class Box (Generic [T]): def __init__ (self, value: T ) -> None : self .value = value def get (self ) -> T: return self .value int_box = Box[int ](42 ) str_box = Box[str ]("hello" ) from pydantic import BaseModel, Fieldfrom datetime import datetimeclass User (BaseModel ): id : int name: str = Field(min_length=1 , max_length=50 ) email: str = Field(pattern=r"^\S+@\S+\.\S+$" ) age: int = Field(ge=0 , le=150 ) created_at: datetime = Field(default_factory=datetime.now) tags: List [str ] = [] user = User(id ="1" , name="Tom" , email="tom@example.com" , age="25" ) print (user.id ) user_dict = user.model_dump() user_json = user.model_dump_json()
十、模块与包管理 10.1 导入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import os from os import path from os import path as p from os import * from . import module from .. import parent from .utils import helper import os import sys import json import csv import re import time from datetime import datetime, timedelta import random import hashlib from pathlib import Path from collections import defaultdict, Counter, namedtuple from typing import * import unittest
10.2 项目结构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 my_project/ # 项目根 ├── main.py # 入口文件 ├── config.py # 配置 ├── models/ # 数据模型包 │ ├── __init__.py # 包标识(可为空,Python 3.3+ 可选) │ ├── user.py │ └── document.py ├── services/ # 业务逻辑包 │ ├── __init__.py │ ├── search.py │ └── rag_engine.py ├── utils/ # 工具包 │ ├── __init__.py │ ├── helpers.py │ └── logger.py ├── tests/ # 测试 │ ├── __init__.py │ └── test_search.py ├── requirements.txt # 依赖清单 └── README.md
1 2 3 4 5 6 7 8 fastapi==0.115 .0 uvicorn[standard]==0.32 .0 pydantic==2.9 .0 httpx==0.27 .0 python-multipart==0.0 .12
十一、Pythonic 编程规范 11.1 命名规范(PEP 8)
类型
规范
示例
模块/包
全小写+下划线
my_module, package_name
类名
大驼峰
MyClass, DocumentStore
函数/方法
全小写+下划线
my_function, get_user_by_id
常量
全大写+下划线
MAX_SIZE, DEFAULT_TIMEOUT
私有属性
单下划线前缀
_internal_value
强私有
双下划线前缀
__password
11.2 代码风格要点 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 evens = [x for x in range (10 ) if x % 2 == 0 ] for idx, val in enumerate (items): pass for name, score in zip (names, scores): pass with open ("file.txt" ) as f: data = f.read() value = d.get("key" , "default" ) if not items: pass try : value = d["key" ] except KeyError: value = "default" if "key" in d: value = d["key" ] else : value = "default" a, b = b, a first, *rest = [1 , 2 , 3 , 4 ] first, *middle, last = [1 , 2 , 3 , 4 ]
十二、Java → Python 常见陷阱对照表
场景
Java 习惯
Python 正确做法
判断相等
== 比较对象引用
== 比较值(数值/字符串),is 比较身份
字符串拼接
"" + var 循环拼接
用f-string 或 "".join()
空判断
str == null / str.isEmpty()
if not s: / if s:
深拷贝
new ArrayList<>(old)
copy.deepcopy(old) 或切片 [:]
整数除法
5 / 2 = 2(整数除)
5 // 2 = 2(地板除),5 / 2 = 2.5(真除法)
作用域
for 循环变量块级作用域
for 循环变量泄漏到外部!
默认参数
自动每次创建新对象
默认参数只求值一次(用 None 占位)
多线程
Thread / synchronized
GIL 限制,用多进程或 asyncio
switch
switch/case
Python 3.10+ match/case,或字典映射
getter/setter
getXxx() / setXxx()
@property 装饰器
作用域泄漏陷阱(重点!) 1 2 3 4 5 6 7 8 9 10 11 i = 100 for i in range (5 ): pass print (i) for idx in range (5 ): pass
十三、速查卡( Cheat Sheet ) 常用操作一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 if x in arr: pass "," .join(["a" , "b" , "c" ]) "a,b,c" .split("," ) d1 | d2 {**d1, **d2} list (dict .fromkeys([1 ,2 ,2 ,3 ])) a, b, c = 1 , 2 , 3 value = x if x > 0 else 0 if 0 <= score <= 100 : pass a, *b, c = [1 , 2 , 3 , 4 , 5 ] a = b = c = [] sorted (d.items(), key=lambda x: x[1 ], reverse=True )"-" * 30 arr_copy = arr[:] arr_copy = arr.copy() arr_copy = list (arr) import copy; arr_deep = copy.deepcopy(arr) dir (str ) help (str .split)
十四、常用标准库速查 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import osos.path.exists("file.txt" ) os.path.join("dir" , "file.txt" ) os.makedirs("a/b/c" , exist_ok=True ) os.listdir("." ) os.getenv("API_KEY" ) from pathlib import Path path = Path("data" ) / "users.json" path.exists() path.read_text(encoding="utf-8" ) path.write_text("content" , encoding="utf-8" ) import rere.search(r"\d+" , "abc123" ) re.findall(r"\d+" , "a1b2c3" ) re.sub(r"\d+" , "X" , "a1b2" ) re.match (r"\d+" , "123abc" ) re.split(r"," , "a,b,c" ) from datetime import datetime, timedeltanow = datetime.now() ts = now.isoformat() parsed = datetime.fromisoformat(ts) dt = now + timedelta(days=7 , hours=2 ) import randomrandom.randint(1 , 100 ) random.choice(["a" , "b" , "c" ]) random.shuffle(arr) random.random() from collections import Counter, dequecounter = Counter(["a" , "b" , "a" , "c" , "a" ]) counter.most_common(2 ) dq = deque(maxlen=100 ) dq.append(1 ) dq.appendleft(0 )
使用建议 :这份笔记不是教科书,是速查手册 。建议先通读一遍建立整体认知,然后边写代码边查阅。重点掌握:列表推导式、字典操作、装饰器、生成器、Type Hints、Dataclass——这六项是后续 FastAPI + AI 开发的语法基石。
版本:v1.0 | 配套:Python练习题 + RAG/Agent学习路线