Python 中常用内置函数分类总结(常用场景速查)

Python内置函数分类速查指南


本文整理了Python中常用的内置函数,分为5大类:

  1. 数学运算类:abs()取绝对值,round()四舍五入,pow()求幂,sum()求和等
  2. 类型转换类:int()/float()数值转换,str()转字符串,list()/tuple()序列转换等
  3. 序列操作类:len()获取长度,sorted()排序,enumerate()获取索引,zip()并行遍历等
  4. 输入输出类:print()输出,input()输入,format()格式化等
  5. 其他常用:type()查看类型,help()获取帮助,eval()执行表达式等

文中提供了每个函数的说明、示例和返回值,并列出了常见场景的推荐函数组合,如使用max()/min()获取极值,set()去重等。


这些内置函数能显著提升编码效率,建议收藏备用。


Python 中常用内置函数分类总结


一、数学运算类

函数 说明 示例 结果
abs(x) 返回绝对值 abs(-5) 5
round(x, n) 四舍五入,保留n位小数 round(3.14159, 2) 3.14
pow(x, y) 返回 x 的 y 次方 pow(2, 3) 8
divmod(a, b) 返回(商, 余数)元组 divmod(10, 3) (3, 1)
sum(iterable) 求和 sum([1,2,3]) 6
max(iterable) 返回最大值 max([3,1,4,2]) 4
min(iterable) 返回最小值 min([3,1,4,2]) 1

二、类型转换类

函数 说明 示例 结果
int(x) 转换为整数 int("123") 123
float(x) 转换为浮点数 float("3.14") 3.14
str(x) 转换为字符串 str(123) "123"
list(iterable) 转换为列表 list("abc") ['a','b','c']
tuple(iterable) 转换为元组 tuple([1,2,3]) (1,2,3)
set(iterable) 转换为集合(去重) set([1,2,2,3]) {1,2,3}
dict(iterable) 转换为字典 dict([(1,'a'),(2,'b')]) {1:'a',2:'b'}
bool(x) 转换为布尔值 bool(0) False
chr(x) ASCII码转字符 chr(65) 'A'
ord(c) 字符转ASCII码 ord('A') 65

三、序列操作类

函数 说明 示例 结果
len(s) 返回长度/元素个数 len([1,2,3]) 3
sorted(iterable) 返回排序后的新列表 sorted([3,1,2]) [1,2,3]
reversed(seq) 反转序列的迭代器 list(reversed([1,2,3])) [3,2,1]
enumerate(iterable) 返回索引-元素对 list(enumerate(['a','b'])) [(0,'a'),(1,'b')]
zip(*iterables) 打包为元组列表 list(zip([1,2],['a','b'])) [(1,'a'),(2,'b')]
range(start,stop) 生成整数序列 list(range(3)) [0,1,2]
all(iterable) 全部为真返回True all([True,True,False]) False
any(iterable) 任一为真返回True any([False,False,True]) True
filter(func, iterable) 过滤序列 list(filter(lambda x:x>2, [1,2,3])) [3]
map(func, iterable) 映射函数到序列 list(map(lambda x:x*2, [1,2,3])) [2,4,6]

四、输入输出类

函数 说明 示例 结果
print(*objects) 打印输出 print("Hello") 控制台输出
input(prompt) 获取用户输入 input("请输入:") 返回字符串
format(value, spec) 格式化字符串 format(3.14, '.1f') '3.1'

五、其他常用函数

函数 说明 示例 结果
type(obj) 返回对象类型 type(123) <class 'int'>
id(obj) 返回对象内存地址 id("abc") 数字地址
isinstance(obj, class) 检查对象类型 isinstance(5, int) True
open(file, mode) 打开文件 open("test.txt", "r") 文件对象
help(func) 查看函数帮助 help(print) 帮助文档
dir(obj) 返回对象属性列表 dir([]) 列表方法列表
eval(expression) 执行字符串表达式 eval("2+3") 5
exec(code) 执行Python代码 exec("a=5") 无返回值

六、常用场景速查

需求 推荐函数
获取列表最大/最小值 max() / min()
字符串转数字 int() / float()
序列去重 set()
快速排序 sorted()
批量处理数据 map() / filter()
获取索引和值 enumerate()
并行遍历多个序列 zip()
判断真值 all() / any()

提示 :Python 3.x 共有 70+ 个内置函数,以上是最常用的一部分。可以使用 dir(__builtins__) 查看所有内置函数列表。

相关推荐
cup115 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi007 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵9 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf9 小时前
Agent 流程编排
后端·python·agent
copyer_xyf10 小时前
Agent RAG
后端·python·agent
copyer_xyf10 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf10 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏