首页  

python内置函数     所属分类 python 浏览量 8
Python 内置了大量实用的函数,无需导入任何模块即可直接使用
输入输出:print(), input()
类型转换:int(), str(), list() 等
数学运算:abs(), sum(), min(), max() 等
序列操作:len(), sorted(), zip(), enumerate() 等
函数式编程:map(), filter(), any(), all() 等
对象操作:type(), isinstance(), getattr() 等
编译执行:eval(), exec(), compile() 等



一、基本输入输出函数 1. print() - 输出函数 # 基本用法 print("Hello, World!") # Hello, World! # 多个参数 print("Name:", "Alice", "Age:", 25) # Name: Alice Age: 25 # 指定分隔符 print("2023", "12", "15", sep="-") # 2023-12-15 # 指定结束符 print("Line 1", end=" ") print("Line 2") # Line 1 Line 2 # 格式化输出 name = "Bob" age = 30 print(f"{name} is {age} years old") # Bob is 30 years old 2. input() - 输入函数 # 基本用法 name = input("Enter your name: ") print(f"Hello, {name}!") # 输入数值(需要类型转换) age = int(input("Enter your age: ")) height = float(input("Enter your height (m): ")) print(f"Age: {age}, Height: {height}m") 二、类型转换函数 3. int(), float(), str(), bool() # 整数转换 print(int(3.14)) # 3 print(int("42")) # 42 print(int("101", 2)) # 5 (二进制转十进制) # 浮点数转换 print(float(10)) # 10.0 print(float("3.14")) # 3.14 # 字符串转换 print(str(100)) # "100" print(str(3.14)) # "3.14" print(str([1, 2, 3])) # "[1, 2, 3]" # 布尔转换 print(bool(0)) # False print(bool(1)) # True print(bool("")) # False print(bool("Hello")) # True print(bool([])) # False print(bool([1, 2])) # True 4. list(), tuple(), set(), dict() # 列表转换 print(list("abc")) # ['a', 'b', 'c'] print(list((1, 2, 3))) # [1, 2, 3] print(list({1, 2, 3})) # [1, 2, 3] # 元组转换 print(tuple([1, 2, 3])) # (1, 2, 3) print(tuple("abc")) # ('a', 'b', 'c') # 集合转换(自动去重) print(set([1, 2, 2, 3, 3])) # {1, 2, 3} print(set("hello")) # {'h', 'e', 'l', 'o'} # 字典转换 items = [("a", 1), ("b", 2)] print(dict(items)) # {'a': 1, 'b': 2} 三、数学运算函数 5. abs(), round(), divmod(), pow() # 绝对值 print(abs(-10)) # 10 print(abs(3.14)) # 3.14 # 四舍五入 print(round(3.14159, 2)) # 3.14 print(round(3.5)) # 4 print(round(2.5)) # 2 (银行家舍入法) # 商和余数 print(divmod(10, 3)) # (3, 1) print(divmod(10.5, 3)) # (3.0, 1.5) # 幂运算 print(pow(2, 3)) # 8 print(pow(2, 3, 3)) # 2 (2^3 % 3) 6. sum(), min(), max() # 求和 numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # 15 print(sum(numbers, 10)) # 25 (从10开始累加) # 最小值/最大值 print(min(3, 1, 4, 1, 5)) # 1 print(max([3, 1, 4, 1, 5])) # 5 # 使用key参数 words = ["apple", "banana", "cherry", "date"] print(min(words, key=len)) # date print(max(words, key=len)) # banana 四、序列操作函数 7. len(), sorted(), reversed(), enumerate() # 长度 print(len("Hello")) # 5 print(len([1, 2, 3])) # 3 print(len({"a": 1, "b": 2})) # 2 # 排序 nums = [3, 1, 4, 1, 5, 9] print(sorted(nums)) # [1, 1, 3, 4, 5, 9] print(sorted(nums, reverse=True)) # [9, 5, 4, 3, 1, 1] # 自定义排序 words = ["apple", "Banana", "cherry", "Date"] print(sorted(words)) # ['Banana', 'Date', 'apple', 'cherry'] print(sorted(words, key=str.lower)) # ['apple', 'Banana', 'cherry', 'Date'] # 反转 nums = [1, 2, 3, 4, 5] rev = reversed(nums) print(list(rev)) # [5, 4, 3, 2, 1] # 枚举 fruits = ["apple", "banana", "cherry"] for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 0: apple # 1: banana # 2: cherry # 指定起始索引 for i, fruit in enumerate(fruits, start=1): print(f"{i}: {fruit}") 8. zip(), range() # zip函数 - 合并多个序列 names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] scores = [85, 90, 95] for name, age, score in zip(names, ages, scores): print(f"{name}: {age} years, score: {score}") # 转成字典 print(dict(zip(names, ages))) # {'Alice': 25, 'Bob': 30, 'Charlie': 35} # range函数 - 生成数字序列 print(list(range(5))) # [0, 1, 2, 3, 4] print(list(range(1, 6))) # [1, 2, 3, 4, 5] 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] 五、迭代器和生成器函数 9. iter(), next(), filter(), map() # iter和next numbers = [1, 2, 3] it = iter(numbers) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 # print(next(it)) # StopIteration异常 # filter函数 - 过滤序列 def is_even(n): return n % 2 == 0 nums = [1, 2, 3, 4, 5, 6] evens = filter(is_even, nums) print(list(evens)) # [2, 4, 6] # 使用lambda表达式 evens = filter(lambda x: x % 2 == 0, nums) print(list(evens)) # [2, 4, 6] # map函数 - 对序列每个元素应用函数 def square(x): return x ** 2 squares = map(square, nums) print(list(squares)) # [1, 4, 9, 16, 25, 36] # 多个序列 a = [1, 2, 3] b = [10, 20, 30] result = map(lambda x, y: x + y, a, b) print(list(result)) # [11, 22, 33] 六、对象操作函数 10. id(), type(), isinstance(), issubclass() # 对象标识 x = [1, 2, 3] y = [1, 2, 3] print(id(x)) # 内存地址(每次运行不同) print(id(y)) # 与x不同 print(x is y) # False # 类型检查 print(type(42)) # <class 'int'> print(type("Hello")) # <class 'str'> print(type([1, 2, 3])) # <class 'list'> # 类型判断 print(isinstance(42, int)) # True print(isinstance("Hello", (str, int))) # True (str或int) # 子类判断 class Animal: pass class Dog(Animal): pass print(issubclass(Dog, Animal)) # True print(issubclass(Dog, object)) # True 11. hasattr(), getattr(), setattr(), delattr() class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Alice", 25) # 检查属性 print(hasattr(p, "name")) # True print(hasattr(p, "height")) # False # 获取属性 print(getattr(p, "name")) # Alice print(getattr(p, "height", "N/A")) # N/A (默认值) # 设置属性 setattr(p, "height", 170) print(p.height) # 170 # 删除属性 delattr(p, "height") # print(p.height) # AttributeError 七、作用域相关函数 12. globals(), locals() x = 10 # 全局变量 def test(): y = 20 # 局部变量 print("局部变量:", locals()) # {'y': 20} print("全局变量:", globals().get('x')) # 10 test() print("全局命名空间:", globals().keys()) 八、编译和执行函数 13. eval(), exec(), compile() # eval - 计算表达式 x = 10 result = eval("x * 2 + 5") print(result) # 25 # exec - 执行代码 code = """ for i in range(3): print(f"Number: {i}") """ exec(code) # compile - 编译代码 code_str = "print('Hello, World!')" compiled = compile(code_str, '<string>', 'exec') exec(compiled) 九、其他实用函数 14. open() - 文件操作 # 写入文件 with open("example.txt", "w") as f: f.write("Hello, World!\n") f.write("This is a test file.\n") # 读取文件 with open("example.txt", "r") as f: content = f.read() print(content) # 逐行读取 with open("example.txt", "r") as f: for line in f: print(line.strip()) 15. help(), dir() # 获取帮助 help(print) # 显示print函数的帮助信息 # 查看对象属性 print(dir([])) # 查看列表的方法 print(dir("hello")) # 查看字符串的方法 # 查看内置函数 import builtins print(dir(builtins)) 16. any(), all() # any - 任意元素为True则返回True print(any([False, False, True])) # True print(any([0, 0, 0])) # False # all - 所有元素为True则返回True print(all([True, True, True])) # True print(all([1, 2, 0])) # False 十、高级应用示例 综合示例:数据处理管道 # 使用多个内置函数处理数据 data = ["10", "20", "30", "40", "50"] # 转换为整数,过滤大于25的数,计算平方 result = list( map( lambda x: x**2, filter( lambda x: x > 25, map(int, data) ) ) ) print(result) # [900, 1600, 2500] # 更简洁的写法(使用列表推导式) result = [x**2 for x in map(int, data) if x > 25] print(result) # [900, 1600, 2500] 综合示例:对象排序 # 复杂对象排序 students = [ {"name": "Alice", "score": 85, "age": 20}, {"name": "Bob", "score": 92, "age": 22}, {"name": "Charlie", "score": 78, "age": 19}, {"name": "David", "score": 92, "age": 21} ] # 按分数降序,年龄升序排序 sorted_students = sorted( students, key=lambda x: (-x["score"], x["age"]) ) for student in sorted_students: print(student)

上一篇    
Python 类型提示(Type Hints)

python 属性访问器

Python知识点及代码示例