Python基础入门之len、abs、sum等内置函数使用汇总
作者:星河耀银海
本文系统梳理了Python自带的70多个内置函数,涵盖数学计算、类型转换、序列操作等类别,帮你建立全局视野,不再死记硬背,掌握这些函数让你的代码更简洁高效,是每个Python开发者必备的速查指南
一、开篇:Python的内置函数
Python自带70多个内置函数(Built-in Functions),——不需要import,随时可用,覆盖了类型转换、数学计算、序列操作、对象信息等方方面面。
你已经在日常编程中大量使用它们了:
# 这些你不用import就能用:
print(len([1, 2, 3])) # 3
print(abs(-5)) # 5
print(sum([1, 2, 3])) # 6
print(type("hello")) # <class 'str'>
print(int("42")) # 42
print(range(10)) # range(0, 10)
print(isinstance(5, int)) # True
这篇文章,我们对Python内置函数做一个系统性的梳理——按类别整理,了解每个函数的用途和典型用法。这不只是一份"速查表",更是帮你建立Python全局视野的指南。
二、数学相关内置函数
2.1 基本数学运算
# abs(x) —— 绝对值
print(abs(-10)) # 10
print(abs(3.14)) # 3.14
print(abs(-3 + 4j)) # 5.0 —— 复数的模
# round(number, ndigits) —— 四舍五入
print(round(3.14159, 2)) # 3.14
print(round(3.14159)) # 3(不指定精度,保留到整数)
print(round(2.5)) # 2 —— ⚠️ 注意:银行家舍入!
# pow(base, exp, mod) —— 幂运算(可带模)
print(pow(2, 10)) # 1024
print(pow(2, 10, 1000)) # 24 —— 等价于 (2**10) % 1000,但更高效
# divmod(a, b) —— 同时返回商和余数
quotient, remainder = divmod(17, 5)
print(f"17 ÷ 5 = {quotient} 余 {remainder}") # 17 ÷ 5 = 3 余 2
# 常用于:分页计算、时间换算
total_minutes = 137
hours, minutes = divmod(total_minutes, 60)
print(f"{hours}小时{minutes}分钟") # 2小时17分钟
2.2 聚合函数
# sum(iterable, start) —— 求和
print(sum([1, 2, 3, 4, 5])) # 15
print(sum([1, 2, 3], 10)) # 16(从10开始加)
# 性能提示:sum()用C实现,比for循环快得多
# min(iterable) / min(a, b, c, ...) —— 最小值
print(min([5, 2, 8, 1, 9])) # 1
print(min(5, 2, 8, 1, 9)) # 1
print(min("python", "java", "c")) # 'c' —— 按字母顺序
# min也支持key参数
words = ["python", "java", "c", "go", "rust"]
print(min(words, key=len)) # 'c' —— 最短的
# max(iterable) —— 最大值
print(max([5, 2, 8, 1, 9])) # 9
print(max(words, key=len)) # 'python' —— 最长的
# 实用组合
scores = [85, 92, 78, 95, 88]
avg = sum(scores) / len(scores)
print(f"平均分: {avg:.1f}, 最高: {max(scores)}, 最低: {min(scores)}")
三、类型转换内置函数
3.1 数值类型转换
# int(x, base) —— 转整数
print(int(3.14)) # 3
print(int("42")) # 42
print(int("1010", 2)) # 10 —— 二进制字符串转十进制
print(int("FF", 16)) # 255 —— 十六进制
print(int("0xFF", 16)) # 255 —— 0x前缀也能处理
# float(x) —— 转浮点数
print(float(42)) # 42.0
print(float("3.14")) # 3.14
print(float("inf")) # inf —— 无穷大
print(float("nan")) # nan —— 非数字
# complex(real, imag) —— 转复数
print(complex(3, 4)) # (3+4j)
print(complex("3+4j")) # (3+4j)
# bool(x) —— 转布尔值
print(bool(1)) # True
print(bool(0)) # False
print(bool([])) # False —— 空列表是假值
print(bool([1, 2])) # True
print(bool("hello")) # True
print(bool("")) # False
3.2 序列类型转换
# list(iterable) —— 转列表
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list((1, 2, 3))) # [1, 2, 3]
# tuple(iterable) —— 转元组
print(tuple([1, 2, 3])) # (1, 2, 3)
# set(iterable) —— 转集合(自动去重)
print(set([1, 2, 2, 3, 3, 3])) # {1, 2, 3}
# dict(**kwargs) 或 dict(mapping) —— 创建字典
print(dict(name="张三", age=25)) # {'name': '张三', 'age': 25}
print(dict([("a", 1), ("b", 2)])) # {'a': 1, 'b': 2}
# frozenset(iterable) —— 不可变集合
fs = frozenset([1, 2, 3])
# fs.add(4) # AttributeError! 不可修改
# str(object) —— 转字符串
print(str(42)) # "42"
print(str([1, 2, 3])) # "[1, 2, 3]"
print(str(None)) # "None"
# bytes(source) —— 创建字节对象
print(bytes([72, 101, 108, 108, 111])) # b'Hello'
print(bytes("Hello", "utf-8")) # b'Hello'
# bytearray(source) —— 可变的字节数组
ba = bytearray(b"Hello")
ba[0] = 104 # 'h'的ASCII码
print(ba) # bytearray(b'hello')
四、序列操作内置函数
4.1 信息获取
# len(s) —— 获取长度
print(len("Python")) # 6
print(len([1, 2, 3, 4, 5])) # 5
print(len({"a": 1, "b": 2})) # 2
# ⚠️ len()是O(1)操作——Python内部记录了长度
4.2 创建和转换序列
# range(start, stop, step) —— 创建整数序列
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# enumerate(iterable, start) —— 带索引的迭代
fruits = ["苹果", "香蕉", "橙子"]
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# 1. 苹果
# 2. 香蕉
# 3. 橙子
# zip(*iterables) —— 并行迭代
names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 张三: 85
# 李四: 92
# 王五: 78
# 矩阵转置(zip的经典应用)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(transposed) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# reversed(sequence) —— 反向迭代
print(list(reversed([1, 2, 3, 4]))) # [4, 3, 2, 1]
print("".join(reversed("Hello"))) # 'olleH'
# sorted(iterable, key, reverse) —— 排序
print(sorted([3, 1, 4, 1, 5])) # [1, 1, 3, 4, 5]
# slice(start, stop, step) —— 创建切片对象
s = slice(1, 5, 2)
print([0, 1, 2, 3, 4, 5, 6, 7, 8, 9][s]) # [1, 3]
# filter(function, iterable) —— 过滤
# map(function, iterable) —— 映射
五、对象信息内置函数
5.1 类型和身份检查
# type(object) —— 获取类型
print(type(42)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
# isinstance(object, classinfo) —— 检查是否为某类型
print(isinstance(42, int)) # True
print(isinstance(42, (int, float))) # True —— 可以是多个类型之一
print(isinstance("hello", str)) # True
print(isinstance([1, 2], (list, tuple))) # True
# issubclass(class, classinfo) —— 检查子类关系
class Animal: pass
class Dog(Animal): pass
print(issubclass(Dog, Animal)) # True
print(issubclass(Dog, object)) # True
# id(object) —— 获取对象的内存地址
a = [1, 2, 3]
b = a
print(id(a)) # 例如: 140234567890
print(id(b)) # 相同——同一个对象
print(id([1, 2, 3])) # 不同——新创建的对象
# hash(object) —— 获取哈希值
print(hash("hello")) # 某个整数
print(hash((1, 2, 3))) # 某个整数
# hash([1, 2, 3]) # TypeError! 列表不可哈希
5.2 属性和能力检查
# dir(object) —— 列出对象的所有属性和方法
print(dir("hello")) # 列出字符串的所有方法
print(dir([])) # 列出列表的所有方法
# hasattr(obj, name) —— 检查是否有某属性
print(hasattr("hello", "upper")) # True
print(hasattr("hello", "foo")) # False
# getattr(obj, name, default) —— 获取属性
print(getattr("hello", "upper")) # <built-in method upper>
print(getattr("hello", "foo", None)) # None —— 不存在返回默认值
# setattr(obj, name, value) —— 设置属性
class Config: pass
cfg = Config()
setattr(cfg, "debug", True)
print(cfg.debug) # True
# callable(object) —— 检查是否为可调用对象
print(callable(print)) # True —— 函数可调用
print(callable(lambda: 1)) # True —— lambda可调用
print(callable(42)) # False —— 数字不可调用
print(callable("hello")) # False —— 字符串不可调用
六、I/O和字符串相关
6.1 输入输出
# print(*objects, sep, end, file, flush)
print("Hello", "World", sep=", ", end="!\n")
# Hello, World!
# 打印到文件
# with open("output.txt", "w") as f:
# print("日志信息", file=f)
# input(prompt) —— 获取用户输入
# name = input("请输入你的名字: ")
# age = int(input("请输入你的年龄: "))
# open(file, mode, ...) —— 打开文件
# with open("data.txt", "r", encoding="utf-8") as f:
# content = f.read()
6.2 字符编码和格式化
# ord(c) —— 字符转Unicode码点
print(ord('A')) # 65
print(ord('中')) # 20013
print(ord('😀')) # 128512
# chr(i) —— Unicode码点转字符
print(chr(65)) # 'A'
print(chr(20013)) # '中'
print(chr(128512)) # '😀'
# repr(object) —— 获取对象的表示形式
print(repr("Hello\nWorld")) # 'Hello\nWorld'
# ascii(object) —— ASCII表示(非ASCII字符转义)
print(ascii("Hello 世界")) # 'Hello 世界'
# format(value, format_spec) —— 格式化
print(format(255, 'x')) # 'ff' —— 十六进制
print(format(255, '#x')) # '0xff'
print(format(3.14159, '.2f')) # '3.14'
# bin(x), oct(x), hex(x) —— 进制转换
print(bin(10)) # '0b1010'
print(oct(10)) # '0o12'
print(hex(255)) # '0xff'
七、函数式编程内置函数
# iter(iterable) —— 获取迭代器 it = iter([1, 2, 3]) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 # next(iterator, default) —— 获取下一个元素 it = iter([1]) print(next(it, "default")) # 1 print(next(it, "default")) # 'default' —— 迭代器耗尽 # any(iterable) —— 任一为True print(any([False, False, True])) # True print(any([0, "", None, False])) # False # all(iterable) —— 全部为True print(all([True, True, True])) # True print(all([True, False, True])) # False
八、最常用的内置函数Top 10
根据使用频率排名
- print() —— 输出
- len() —— 获取长度
- type() —— 查看类型
- int() / str() / float() —— 类型转换
- range() —— 生成序列
- list() / dict() / tuple() / set() —— 创建容器
- input() —— 获取输入
- enumerate() / zip() —— 序列操作
- isinstance() —— 类型检查
- sorted() / min() / max() / sum() —— 聚合
熟练掌握这10类函数,能覆盖日常编程90%的需求
九、总结
Python的70+内置函数是语言设计哲学"电池已包含"(Batteries Included)的体现。它们覆盖了数学计算、类型转换、序列操作、对象信息、I/O、编码转换等方方面面。
使用建议:
- 优先使用内置函数——C实现,速度快,bug少
- 了解但不死记——知道有哪些就行,需要时查
- 善用内置函数组合——
sum(map(int, data))之类的链式调用
以上就是Python基础入门之len、abs、sum等内置函数使用汇总的详细内容,更多关于Python内置函数的资料请关注脚本之家其它相关文章!
