# 内置函数 # python提供了丰富的内置函数,这些函数无需导入任何模块即可直接使用。内置函数涵盖了数学运算、类型转换、序列操作、输入输出等各个方面,是Python编程的基础工具。 # 分类 主要函数 用途 # 数学运算 abs(), round(), pow(), max(), min() 数值计算 # 类型转换 int(), float(), str(), bool(), list() 数据类型转换 # 序列操作 len(), sum(), sorted(), reversed() 序列处理 # 输入输出 print(), input() 用户交互 # 迭代器 range(), enumerate(), zip(), map() 迭代处理 # 对象操作 type(), isinstance(), hasattr() 对象检查 # 基本数学函数 # abs() - 返回绝对值 print(abs(-5)) # 5 print(abs(3.14)) # 3.14 # round() - 四舍五入 print(round(3.14159, 2)) # 3.14 print(round(3.5)) # 4 # pow() - 幂运算 print(pow(2, 3)) # 8 print(pow(2, 3, 5)) # 3 (2^3 % 5) # divmod() - 返回商和余数 quotient, remainder = divmod(10, 3) print(quotient, remainder) # 3 1 # 最值函数 # max() / min() - 最大值/最小值 numbers = [1, 5, 2, 8, 3] print(max(numbers)) # 8 print(min(numbers)) # 1 # 支持多个参数 print(max(1, 5, 3)) # 5 print(min(1, 5, 3)) # 1 # 支持字符串比较 print(max("abcXYZ")) # 'c'(按Unicode顺序) print(min("abcXYZ")) # 'X' # 基本类型转换 # int(), float(), str(), bool() print(int("123")) # 123 print(float("3.14")) # 3.14 print(str(456)) # "456" print(bool(0)) # False print(bool(1)) # True print(bool("")) # False print(bool("hello")) # True # 集合类型转换 # list(), tuple(), set(), dict() 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} (自动去重) # dict() 转换 pairs = [("a", 1), ("b", 2)] print(dict(pairs)) # {'a': 1, 'b': 2} # 特殊转换函数 # chr() / ord() - 字符与ASCII码转换 print(chr(65)) # 'A' print(ord("A")) # 65 # bin(), oct(), hex() - 进制转换 print(bin(10)) # '0b1010' print(oct(10)) # '0o12' print(hex(255)) # '0xff' # 长度和统计 # len() - 获取序列长度 print(len("python")) # 6 print(len([10, 20, 30])) # 3 print(len({"a": 1, "b": 2})) # 2 # sum() - 求和 scores = [80, 90, 75] print(sum(scores)) # 245 print(sum([1, 2, 3], 10)) # 16 (可指定初始值) # 排序和反转 # sorted() - 返回排序后的新列表 letters = ["b", "d", "a", "c"] print(sorted(letters)) # ['a', 'b', 'c', 'd'] print(sorted(letters, reverse=True)) # ['d', 'c', 'b', 'a'] # reversed() - 生成反向迭代器 nums = [1, 2, 3] for n in reversed(nums): print(n, end=" ") # 输出: 3 2 1 print(list(reversed(nums))) # [3, 2, 1] # 枚举和打包 # enumerate() - 枚举索引和元素 foods = ["apple", "banana", "pear"] for idx, food in enumerate(foods): print(idx, food) # 0 apple, 1 banana, 2 pear # zip() - 并行打包多个序列 names = ["Tom", "Jerry"] ages = [8, 9] for name, age in zip(names, ages): print(f"{name} is {age} years old") # 逻辑判断 # any() / all() - 逻辑判断 flags = [True, False, True] print(any(flags)) # True,只要有一个为True返回True print(all(flags)) # False,全部为True才返回True # 实际应用 scores = [80, 70, 65, 90] print(all(s > 60 for s in scores)) # 检查是否都及格 -> True print(any(s < 60 for s in scores)) # 是否有挂科 -> False # input() 函数 # input() 从标准输入(通常为键盘)获取用户输入,返回字符串类型。 # 注意事项: # input() 返回的始终是字符串 # 需要数字时要用 int() 或 float() 转换 # 可以显示提示信息 # 基本用法 name = input("请输入你的名字: ") print(f"你好, {name}!") # 类型转换 age = int(input("请输入你的年龄: ")) print(f"你明年就 {age + 1} 岁了!") # print() 向标准输出(控制台)打印内容,支持多种格式参数。 # 基本语法:print(value1, value2, ..., sep="分隔符", end="结束符") print("Python", "很", "好用", sep="--") # 输出: Python--很--好用 print("Hello", end="!") # 输出: Hello! # 格式化输出 x = 5 print(f"x 的平方是 {x**2}") # 输出: x 的平方是 25 # 输出变量和表达式 numbers = [1, 2, 3] print("列表:", numbers) # 输出: 列表: [1, 2, 3] # range() 函数 # range() 生成连续整数序列,返回可迭代对象(不是列表)。 # 基本用法 # 语法: # range(stop):从 0 开始,到 stop(不包含 stop) # range(start, stop):从 start 开始,到 stop(不包含 stop) # range(start, stop, step):从 start 开始,步长为 step # 注意事项: # Python 3 中,range() 返回的不是列表 # 需要用 list(range(...)) 转换为列表 # stop 不包含在结果序列内 for i in range(5): print(i, end=" ") # 输出: 0 1 2 3 4 for i in range(3, 8): print(i, end=" ") # 输出: 3 4 5 6 7 for i in range(0, 10, 2): print(i, end=" ") # 输出: 0 2 4 6 8 for i in range(5, 0, -2): print(i, end=" ") # 输出: 5 3 1 # enumerate() 函数 # enumerate(iterable, start=0) 返回枚举对象,包含索引和值。 fruits = ["apple", "banana", "cherry"] for i, fruit in enumerate(fruits): print(i, fruit) # 输出: # 0 apple # 1 banana # 2 cherry # 自定义起始索引 for i, fruit in enumerate(fruits, start=1): print(i, fruit) # 输出: # 1 apple # 2 banana # 3 cherry # zip() 函数 # zip(*iterables) 并行遍历多个可迭代对象,将相同位置的元素打包成元组。 # zip() 函数 # zip(*iterables) 并行遍历多个可迭代对象,将相同位置的元素打包成元组。 # 注意事项: # 如果传入的可迭代对象长度不同,则以最短的为准 # 多余的元素被忽略 names = ["Tom", "Jerry", "Spike"] scores = [95, 98, 88] for name, score in zip(names, scores): print(name, score) # 输出: # Tom 95 # Jerry 98 # Spike 88 # 序列解包 pairs = [("a", 1), ("b", 2), ("c", 3)] letters, numbers = zip(*pairs) print(letters) # ('a', 'b', 'c') print(numbers) # (1, 2, 3) # map() 函数 # map(func, iterable) 对可迭代对象的每个元素应用函数,返回新的迭代器。 # 将字符串转换为大写 words = ["hello", "world", "python"] upper_words = list(map(str.upper, words)) print(upper_words) # ['HELLO', 'WORLD', 'PYTHON'] # 使用lambda函数 numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) print(squared) # [1, 4, 9, 16] # filter() 函数 # filter(func, iterable) 筛选出使函数返回 True 的元素,返回新的迭代器。 # 过滤出长度大于5的单词 words = ["apple", "banana", "cat", "elephant"] long_words = list(filter(lambda w: len(w) > 5, words)) print(long_words) # ['banana', 'elephant'] # 过滤出偶数 numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4, 6] # 注意事项: # map 和 filter 都返回迭代器 # 需要用 list() 或 for 循环取出结果 # 常与 lambda 表达式配合使用 # reversed() 函数 # 反向遍历 for c in reversed("abcde"): print(c, end=" ") # e d c b a # 转换为列表 nums = [1, 2, 3] reversed_nums = list(reversed(nums)) print(reversed_nums) # [3, 2, 1] # sorted() 函数 # sorted(iterable, key=None, reverse=False) 返回排序后的新列表,不修改原数据。 # 基本排序 numbers = [3, 1, 4, 1, 5] print(sorted(numbers)) # [1, 1, 3, 4, 5] # 自定义排序 nums = [-3, 2, 1, -5] print(sorted(nums, key=abs)) # [1, 2, -3, -5] (按绝对值排序) print(sorted(nums, key=abs, reverse=True)) # [-5, -3, 2, 1] # 字符串排序 words = ["apple", "banana", "cherry", "date"] print(sorted(words, key=len)) # ['date', 'apple', 'banana', 'cherry'] (按长度排序) # 类型检查函数 # type() - 获取对象类型 print(type("hello")) # print(type([1, 2, 3])) # # isinstance() - 检查对象类型 print(isinstance(5, int)) # True print(isinstance(5, float)) # False print(isinstance(5, (int, float))) # True (支持类型元组) # 属性操作函数 class Student: def __init__(self, name): self.name = name s = Student("Tom") # hasattr() - 检查对象是否有指定属性 print(hasattr(s, "name")) # True print(hasattr(s, "age")) # False # getattr() - 获取对象属性值 print(getattr(s, "name")) # Tom print(getattr(s, "age", "N/A")) # N/A (提供默认值) # setattr() - 设置对象属性 setattr(s, "age", 20) print(s.age) # 20 # delattr() - 删除对象属性 delattr(s, "age") print(hasattr(s, "age")) # False # 其他 # callable() - 检查对象是否可调用 print(callable(print)) # True print(callable(len)) # True print(callable(10)) # False # dir() - 返回对象的所有属性列表 print(dir(s)) # 显示s的所有属性和方法名 # vars() - 返回对象的属性字典 print(vars(s)) # {'name': 'Tom'} # id() - 返回对象的唯一标识 print(id(s)) # 内存地址 # bool() - 转换为布尔值 print(bool([1, 2, 3])) # True print(bool([])) # False print(bool(0)) # False print(bool("hello")) # True # reduce() 函数 # reduce(func, iterable[, initial]) 对可迭代对象执行累积计算,需要从 functools 导入。 from functools import reduce numbers = [1, 2, 3, 4] # 连乘:1*2*3*4 product = reduce(lambda x, y: x * y, numbers) print(product) # 24 # 连加:1+2+3+4 total = reduce(lambda x, y: x + y, numbers) print(total) # 10 # 带初始值 result = reduce(lambda x, y: x + y, numbers, 10) print(result) # 20 (10 + 1 + 2 + 3 + 4) # 函数式编程组合 # 链式使用内置函数 numbers = [5, 2, 8, 1, 9, 3] result = sorted(filter(lambda x: x > 3, numbers)) print(result) # [5, 8, 9] # 使用生成器表达式 total = sum(x * 2 for x in numbers if x % 2 == 0) print(total) # 20