以下列出 Python 中高频使用的内置函数与标准库模块,适合日常开发快速翻阅。每个条目附简要说明和典型用法。
一、常用内置函数
输入输出
print(*objects, sep=' ', end='\n')— 打印对象,可自定义分隔符和结尾符。input(prompt)— 从标准输入读取一行字符串。
类型与转换
type(obj)— 返回对象类型。isinstance(obj, classinfo)— 检查对象是否为某类型或元组中任一类型。int(x, base=10)/float(x)/str(x)/bool(x)— 基本类型转换。list(iterable)/tuple(iterable)/set(iterable)/dict(**kwargs)— 构造容器。bytes(s, encoding)/str(b, encoding)— 字符串与字节互转。chr(i)/ord(c)— 整数与字符互转(Unicode)。hex(x)/oct(x)/bin(x)— 整数转为十六/八/二进制字符串。
数学与逻辑
abs(x)— 绝对值。round(number, ndigits)— 四舍五入。pow(base, exp, mod)— 幂运算,可带模。divmod(a, b)— 返回商和余数元组。min(iterable)/max(iterable)/sum(iterable, start)— 极值、求和。any(iterable)/all(iterable)— 任意True / 全部True。
序列与迭代
len(s)— 返回长度。range(start, stop, step)— 不可变整数序列,常用于循环。enumerate(iterable, start=0)— 带索引迭代。zip(*iterables)— 并行迭代,返回元组。sorted(iterable, key=None, reverse=False)— 返回新排序列表。reversed(sequence)— 反转迭代。slice(start, stop, step)— 切片对象。
高阶函数(常用)
map(function, iterable)— 对每个元素应用函数,返回迭代器。filter(function, iterable)— 筛选出函数返回True的元素。zip(*iterables)— 组合元素。functools.reduce(function, iterable)— 累积计算(需从functools导入)。
对象与属性
dir(obj)— 返回对象的属性列表。getattr(obj, name, default)/setattr(obj, name, value)/hasattr(obj, name)— 动态属性访问。id(obj)— 返回对象内存地址(身份标识)。isinstance(obj, classinfo)/issubclass(cls, classinfo)— 类关系检查。callable(obj)— 检查对象是否可调用。vars(obj)— 返回对象的dict属性。
文件与资源
open(file, mode='r', encoding=None)— 打开文件,推荐配合with使用。help(obj)— 查看帮助文档。
其他常用
eval(expression)/exec(code)— 执行字符串表达式或代码块(谨慎使用)。globals()/locals()— 返回全局/局部命名空间字典。reversed(seq)— 反向迭代器。ascii(obj)— 返回可打印的字符串表示(非ASCII转义)。
二、常用标准库速查
| 模块 | 主要用途 | 常用函数/类 |
|------|----------|--------------|
| os | 系统交互 | os.path.join, os.listdir, os.getenv, os.makedirs |
| sys | 解释器交互 | sys.argv, sys.exit, sys.path, sys.version |
| pathlib | 面向对象路径操作 | Path.cwd(), Path.home(), .joinpath(), .read_text(), .glob() |
| shutil | 高级文件操作 | shutil.copy, shutil.move, shutil.rmtree, shutil.make_archive |
| logging | 日志记录 | logging.basicConfig, logger.info, logger.exception |
| datetime | 日期时间处理 | datetime.now(), datetime.strptime, timedelta |
| json | JSON 编解码 | json.dumps, json.loads, json.dump, json.load |
| csv | CSV 文件读写 | csv.reader, csv.writer, csv.DictReader |
| re | 正则表达式 | re.search, re.match, re.findall, re.sub |
| collections | 高级容器 | namedtuple, deque, defaultdict, Counter, OrderedDict |
| itertools | 迭代器工具 | itertools.chain, product, permutations, groupby, accumulate |
| functools | 高阶函数工具 | functools.lru_cache, reduce, partial, wraps |
| random | 随机数生成 | random.random, randint, choice, shuffle, sample |
| math | 数学函数 | math.sqrt, ceil, floor, pi, e, sin, log |
| statistics | 统计计算 | mean, median, stdev |
| subprocess | 运行子进程 | subprocess.run, Popen |
| argparse | 命令行参数解析 | ArgumentParser, add_argument, parse_args |
| configparser | 配置文件处理 | ConfigParser, read, get |
| pickle | 对象序列化 | pickle.dump, pickle.load (仅限可信数据) |
| hashlib | 哈希算法 | hashlib.md5, sha256, sha512 |
| base64 | Base64 编解码 | base64.b64encode, b64decode |
| uuid | 生成通用唯一标识符 | uuid4() |
| time | 时间访问与转换 | time.sleep, time.time, time.localtime |
| threading | 多线程 | Thread, Lock, Event |
| multiprocessing | 多进程 | Process, Pool, Queue |
| asyncio | 异步IO | async def, await, asyncio.run, gather |
| unittest | 单元测试框架 | unittest.TestCase, setUp, assertEqual |
| pdb | 调试器 | pdb.set_trace() |
三、快速检索示例
需求:从列表中筛选出所有偶数并求和
nums = [1, 2, 3, 4, 5, 6]
even_sum = sum(x for x in nums if x % 2 == 0)
# 或使用 filter 和 lambda
even_sum = sum(filter(lambda x: x % 2 == 0, nums))
需求:读取 JSON 配置文件并获取某项值
import json
with open('config.json', 'r', encoding='utf-8') as f:
config = json.load(f)
db_host = config.get('database', {}).get('host', 'localhost')
需求:统计字符串中每个单词出现次数
from collections import Counter
text = "apple banana apple orange banana apple"
word_counts = Counter(text.split())
print(word_counts.most_common(2)) # [('apple', 3), ('banana', 2)]
需求:列出当前目录下所有 .py 文件并按修改时间排序
from pathlib import Path
py_files = sorted(Path.cwd().glob('*.py'), key=lambda f: f.stat().st_mtime)
for f in py_files:
print(f.name)
以上速查覆盖了日常编码 80% 以上的高频操作,建议收藏备用。