🔧 21. 内置函数大全

本章概述

Python 常用内置函数速查表,方便快速查阅。 预计学习时间:30 分钟(浏览)


21.1 数学运算

函数说明示例
abs(x)绝对值abs(-5)5
round(x, n)四舍五入round(3.14159, 2)3.14
pow(x, y)x的y次方pow(2, 3)8
divmod(a, b)商和余数divmod(10, 3)(3, 1)
max(iterable)最大值max([1, 5, 3])5
min(iterable)最小值min([1, 5, 3])1
sum(iterable)求和sum([1, 2, 3])6
len(s)长度len("hello")5
print(abs(-10))        # 10
print(round(3.7))      # 4
print(pow(2, 10))      # 1024
print(divmod(17, 5))   # (3, 2)
print(max(3, 7, 2))    # 7
print(min(3, 7, 2))    # 2
print(sum([1, 2, 3, 4, 5]))  # 15
print(len("Python"))   # 6

21.2 类型转换

函数说明示例
int(x)转整数int("123")123
float(x)转浮点数float("3.14")3.14
str(x)转字符串str(123)"123"
bool(x)转布尔值bool(0)False
list(x)转列表list("abc")['a','b','c']
tuple(x)转元组tuple([1,2,3])(1,2,3)
set(x)转集合set([1,2,2,3]){1,2,3}
dict(x)转字典dict([('a',1)]){'a':1}
chr(x)数字转字符chr(65)'A'
ord(x)字符转数字ord('A')65
hex(x)转十六进制hex(255)'0xff'
oct(x)转八进制oct(8)'0o10'
bin(x)转二进制bin(3)'0b11'
print(int("42"))       # 42
print(float("3.14"))   # 3.14
print(str(100))        # '100'
print(bool([]))        # False
print(list("hello"))   # ['h', 'e', 'l', 'l', 'o']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3}
print(chr(65))         # 'A'
print(ord('A'))        # 65
print(hex(255))        # '0xff'
print(bin(10))         # '0b1010'

21.3 序列操作

函数说明示例
sorted(iterable)排序sorted([3,1,2])[1,2,3]
reversed(seq)反转list(reversed([1,2,3]))[3,2,1]
enumerate(seq)带索引枚举list(enumerate(['a','b']))[(0,'a'),(1,'b')]
zip(*iterables)打包list(zip([1,2],['a','b']))[(1,'a'),(2,'b')]
range(start, stop, step)生成范围list(range(5))[0,1,2,3,4]
map(func, iterable)映射list(map(str, [1,2,3]))['1','2','3']
filter(func, iterable)过滤list(filter(bool, [0,1,2]))[1,2]
reduce(func, iterable)累积reduce(lambda a,b:a+b, [1,2,3])6
any(iterable)任一为真any([False, True, False])True
all(iterable)全部为真all([True, True, False])False
# sorted 排序
print(sorted([3, 1, 4, 1, 5, 9]))  # [1, 1, 3, 4, 5, 9]
print(sorted([3, 1, 4], reverse=True))  # [4, 3, 1]
print(sorted(["apple", "banana", "cherry"], key=len))  # 按长度排序
 
# enumerate 枚举
for i, fruit in enumerate(["苹果", "香蕉", "橙子"]):
    print(i, fruit)
 
# zip 打包
names = ["张三", "李四", "王五"]
ages = [18, 19, 20]
for name, age in zip(names, ages):
    print(name, age)
 
# range 范围
for i in range(10):
    print(i)
 
# any / all
print(any([0, "", None, 1]))  # True(有一个真值)
print(all([1, "hello", True]))  # True(全是真值)

21.4 对象操作

函数说明示例
type(obj)查看类型type(123)<class 'int'>
isinstance(obj, class)判断类型isinstance(1, int)True
id(obj)内存地址id(x) → 内存地址
dir(obj)查看属性方法dir(str) → 方法列表
hasattr(obj, name)是否有属性hasattr(s, 'upper')True
getattr(obj, name)获取属性getattr(s, 'upper') → 方法
setattr(obj, name, value)设置属性setattr(obj, 'x', 10)
delattr(obj, name)删除属性delattr(obj, 'x')
callable(obj)是否可调用callable(print)True
help(obj)查看帮助help(str)
# type 和 isinstance
print(type(123))           # <class 'int'>
print(isinstance(123, int)) # True
print(isinstance(123, (int, float)))  # True(是其中一种就行)
 
# dir 查看属性和方法
print(dir("hello"))  # 列出字符串的所有方法
 
# hasattr / getattr / setattr
s = "hello"
print(hasattr(s, "upper"))  # True
func = getattr(s, "upper")
print(func())  # HELLO
 
# help 帮助
help(str.split)  # 查看split方法的帮助

21.5 输入输出

函数说明示例
print(*objects)打印输出print("hello")
input(prompt)输入name = input("请输入姓名:")
open(file, mode)打开文件f = open("a.txt", "r")
# print
print("Hello", "World", sep="-", end="!\n")  # Hello-World!
 
# input
name = input("请输入你的名字:")
print(f"你好,{name}")
 
# open
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Hello World")

21.6 其他常用

函数说明示例
eval(expr)执行表达式eval("1 + 2 * 3")7
exec(code)执行代码exec("print('hello')")
compile(source, filename, mode)编译代码
globals()全局变量字典globals()
locals()局部变量字典locals()
vars(obj)对象的属性字典vars(obj)
hash(obj)哈希值hash("hello")
id(obj)内存地址id(x)
repr(obj)官方字符串表示repr(x)
format(value, spec)格式化format(3.14, '.2f')'3.14'
iter(obj)获取迭代器iter([1,2,3])
next(iterator)下一个值next(it)
slice(start, stop, step)切片对象slice(1, 5, 2)
super()父类对象super().method()
__import__(name)导入模块__import__('math')
# eval 执行表达式
result = eval("2 + 3 * 4")
print(result)  # 14
 
# format 格式化
print(format(3.14159, '.2f'))   # 3.14
print(format(100, ','))         # 100
print(format(100, 'b'))         # 1100100(二进制)
 
# hash 哈希
print(hash("hello"))
print(hash(123))

慎用 eval 和 exec

  • 不要执行不可信的代码,有安全风险
  • 用户输入的内容不要直接传给 eval

21.7 常用函数分类速记

必记(最常用)

# 输出
print()
 
# 类型
int(), float(), str(), bool(), list(), dict(), set(), tuple()
 
# 序列
len(), max(), min(), sum(), sorted(), range(), enumerate(), zip()
 
# 判断
type(), isinstance()
 
# 输入输出
input(), open()

进阶(常用)

# 高阶函数
map(), filter(), any(), all()
 
# 对象操作
dir(), help(), getattr(), hasattr()
 
# 数学
abs(), round(), pow(), divmod()
 
# 转换
chr(), ord(), hex(), bin(), oct()

了解(偶尔用)

eval(), exec(), compile(), globals(), locals(), vars(),
hash(), id(), repr(), format(), iter(), next(), slice(),
super(), __import__(), callable(), reversed()

🔗 相关章节


📝 我的笔记

在这里记录你常用的函数和使用技巧

# 你的练习代码
 

✅ 本章检查清单

  • 掌握常用的类型转换函数
  • 掌握常用的序列操作函数
  • 会使用 sorted、enumerate、zip 等常用函数
  • 了解 any 和 all 的用法
  • 会使用 type 和 isinstance 判断类型
  • 了解 map、filter 等高阶函数