前言 Python内置函数是Python编程语言中预先定义的函数,它们嵌入到Python解释器中,任何时候都能直接使用,无需导入任何模块。这些内置函数的存在极大地提升了程序员的开发效率和程序的可读性。掌握Python内置函数是每个Python开发者必备的基础技能。本文将系统地介绍Python中最常用的内置函数,并提供实用的代码示例。
一、数学运算函数 (一)abs() - 绝对值函数 abs()
函数返回数字的绝对值。
1 2 3 4 5 6 7 8 9 print (abs (-5 )) print (abs (5 )) print (abs (-3.14 )) print (abs (3 +4j ))
(二)round() - 四舍五入函数 round()
函数对数字进行四舍五入。
1 2 3 4 5 6 7 print (round (3.14159 )) print (round (3.14159 , 2 )) print (round (3.14159 , 4 )) print (round (-2.675 , 2 ))
(三)pow() - 幂运算函数 pow()
函数计算x的y次幂。
1 2 3 4 5 6 print (pow (2 , 3 )) print (pow (2 , -1 )) print (pow (2 , 3 , 5 ))
(四)sum() - 求和函数 sum()
函数对可迭代对象中的数字进行求和。
1 2 3 4 5 6 7 8 9 numbers = [1 , 2 , 3 , 4 , 5 ] print (sum (numbers)) print (sum (numbers, 10 )) print (sum ((1 , 2 , 3 )))
(五)min() 和 max() - 最值函数 min()
和max()
函数分别返回最小值和最大值。
1 2 3 4 5 6 7 8 9 10 11 12 print (min (1 , 5 , 3 , 9 )) print (max (1 , 5 , 3 , 9 )) numbers = [3 , 1 , 4 , 1 , 5 , 9 ] print (min (numbers)) print (max (numbers)) print (min ('hello' )) print (max ('hello' ))
二、类型转换函数 (一)int() - 整数转换 int()
函数将其他类型转换为整数。
1 2 3 4 5 6 7 8 9 10 11 12 print (int (3.14 )) print (int (-2.8 )) print (int ('123' )) print (int ('-456' )) print (int ('1010' , 2 )) print (int ('FF' , 16 )) print (int ('77' , 8 ))
(二)float() - 浮点数转换 float()
函数将其他类型转换为浮点数。
1 2 3 4 5 6 7 8 9 10 print (float (5 )) print (float ('3.14' )) print (float ('-2.5' )) print (float ('1e-3' )) print (float ('2.5e2' ))
(三)str() - 字符串转换 str()
函数将其他类型转换为字符串。
1 2 3 4 5 6 7 8 9 10 print (str (123 )) print (str (3.14 )) print (str (True )) print (str (False )) print (str ([1 , 2 , 3 ]))
(四)bool() - 布尔值转换 bool()
函数将其他类型转换为布尔值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 print (bool (1 )) print (bool (0 )) print (bool (-1 )) print (bool ('hello' )) print (bool ('' )) print (bool ([1 , 2 , 3 ])) print (bool ([])) print (bool ({'a' : 1 })) print (bool ({}))
(五)list()、tuple()、set() - 容器类型转换 这些函数用于在不同容器类型之间进行转换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 print (list ('hello' )) print (list ((1 , 2 , 3 ))) print (tuple ([1 , 2 , 3 ])) print (set ([1 , 2 , 2 , 3 , 3 ])) print (set ('hello' ))
三、序列操作函数 (一)len() - 长度函数 len()
函数返回对象的长度或元素个数。
1 2 3 4 5 6 7 8 9 10 11 12 print (len ('hello' )) print (len ('你好世界' )) print (len ([1 , 2 , 3 , 4 ])) print (len ({'a' : 1 , 'b' : 2 })) print (len ({1 , 2 , 3 }))
(二)range() - 范围函数 range()
函数生成数字序列。
1 2 3 4 5 6 7 8 9 10 11 print (list (range (5 ))) print (list (range (1 , 6 ))) print (list (range (0 , 10 , 2 ))) print (list (range (10 , 0 , -1 ))) for i in range (3 ): print (f"第{i+1 } 次循环" )
(三)enumerate() - 枚举函数 enumerate()
函数为可迭代对象添加索引。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 fruits = ['apple' , 'banana' , 'orange' ] for index, fruit in enumerate (fruits): print (f"{index} : {fruit} " ) for index, fruit in enumerate (fruits, start=1 ): print (f"{index} : {fruit} " )
(四)zip() - 打包函数 zip()
函数将多个可迭代对象打包成元组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 names = ['Alice' , 'Bob' , 'Charlie' ] ages = [25 , 30 , 35 ] for name, age in zip (names, ages): print (f"{name} is {age} years old" ) scores1 = [85 , 90 , 78 ] scores2 = [88 , 92 , 80 ] scores3 = [90 , 85 , 82 ] for s1, s2, s3 in zip (scores1, scores2, scores3): print (f"总分: {s1 + s2 + s3} " )
(五)sorted() - 排序函数 sorted()
函数对可迭代对象进行排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 numbers = [3 , 1 , 4 , 1 , 5 , 9 ] print (sorted (numbers)) print (sorted (numbers, reverse=True )) words = ['banana' , 'apple' , 'cherry' ] print (sorted (words)) print (sorted (words, key=len )) students = [('Alice' , 85 ), ('Bob' , 90 ), ('Charlie' , 78 )] print (sorted (students, key=lambda x: x[1 ]))
(六)reversed() - 反转函数 reversed()
函数返回反转的迭代器。
1 2 3 4 5 6 7 8 9 10 11 numbers = [1 , 2 , 3 , 4 , 5 ] print (list (reversed (numbers))) print (list (reversed ('hello' ))) print ('' .join(reversed ('hello' ))) for item in reversed ([1 , 2 , 3 ]): print (item)
四、逻辑判断函数 (一)all() - 全部为真判断 all()
函数判断可迭代对象中的所有元素是否都为真。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 print (all ([True , True , True ])) print (all ([True , False , True ])) print (all ([])) print (all ([1 , 2 , 3 ])) print (all ([1 , 0 , 3 ])) print (all (['hello' , 'world' ])) print (all (['hello' , '' ])) scores = [85 , 90 , 78 , 92 ] print (all (score >= 60 for score in scores))
(二)any() - 任一为真判断 any()
函数判断可迭代对象中是否有任一元素为真。
1 2 3 4 5 6 7 8 9 10 11 12 print (any ([False , False , True ])) print (any ([False , False , False ])) print (any ([])) print (any ([0 , 0 , 1 ])) print (any ([0 , 0 , 0 ])) scores = [85 , 45 , 78 , 92 ] print (any (score < 60 for score in scores))
五、输入输出函数 (一)print() - 输出函数 print()
函数用于输出信息到控制台。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 print ("Hello, World!" )print ("Name:" , "Alice" , "Age:" , 25 )print ("apple" , "banana" , "orange" , sep=", " )print ("Hello" , end=" " )print ("World" )with open ("output.txt" , "w" ) as f: print ("Hello, File!" , file=f)
input()
函数用于从用户获取输入。
1 2 3 4 5 6 7 8 9 10 11 12 name = input ("请输入您的姓名: " ) print (f"您好, {name} !" )age = int (input ("请输入您的年龄: " )) print (f"您今年{age} 岁" )numbers = input ("请输入多个数字(用空格分隔): " ).split() numbers = [int (x) for x in numbers] print (f"您输入的数字是: {numbers} " )
六、高级函数 (一)map() - 映射函数 map()
函数将函数应用到可迭代对象的每个元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 numbers = [1 , 2 , 3 , 4 , 5 ] squares = list (map (lambda x: x**2 , numbers)) print (squares) str_numbers = ['1' , '2' , '3' , '4' , '5' ] int_numbers = list (map (int , str_numbers)) print (int_numbers) list1 = [1 , 2 , 3 ] list2 = [4 , 5 , 6 ] result = list (map (lambda x, y: x + y, list1, list2)) print (result)
(二)filter() - 过滤函数 filter()
函数过滤可迭代对象中满足条件的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] even_numbers = list (filter (lambda x: x % 2 == 0 , numbers)) print (even_numbers) words = ['apple' , 'banana' , 'cherry' , 'date' ] long_words = list (filter (lambda x: len (x) > 5 , words)) print (long_words) data = [1 , None , 3 , None , 5 ] filtered_data = list (filter (None , data)) print (filtered_data)
(三)isinstance() - 类型检查函数 isinstance()
函数检查对象是否为指定类型的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 print (isinstance (5 , int )) print (isinstance (5.0 , float )) print (isinstance ('hello' , str )) print (isinstance ([1 , 2 , 3 ], list )) print (isinstance (5 , (int , float ))) print (isinstance (5.0 , (int , float ))) print (isinstance ('5' , (int , float ))) def safe_divide (a, b ): if not isinstance (a, (int , float )) or not isinstance (b, (int , float )): raise TypeError("参数必须是数字类型" ) if b == 0 : raise ValueError("除数不能为零" ) return a / b
(四)hasattr()、getattr()、setattr() - 属性操作函数 这些函数用于动态操作对象的属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Person : def __init__ (self, name, age ): self .name = name self .age = age person = Person("Alice" , 25 ) print (hasattr (person, 'name' )) print (hasattr (person, 'salary' )) print (getattr (person, 'name' )) print (getattr (person, 'salary' , 0 )) setattr (person, 'salary' , 50000 )print (person.salary)
七、其他常用函数 (一)id() - 对象标识函数 id()
函数返回对象的唯一标识符。
1 2 3 4 5 6 7 8 9 10 11 a = [1 , 2 , 3 ] b = [1 , 2 , 3 ] c = a print (id (a)) print (id (b)) print (id (c)) print (a is c) print (a is b) print (a == b)
(二)type() - 类型获取函数 type()
函数返回对象的类型。
1 2 3 4 5 6 7 8 9 10 print (type (5 )) print (type (5.0 )) print (type ('hello' )) print (type ([1 , 2 , 3 ])) if type (5 ) == int : print ("5是整数" )
(三)dir() - 属性列表函数 dir()
函数返回对象的所有属性和方法列表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 print (dir (str ))print (dir (list ))print (dir ())class MyClass : def __init__ (self ): self .attr1 = "value1" def method1 (self ): pass obj = MyClass() print (dir (obj))
(四)help() - 帮助函数 help()
函数显示对象的帮助信息。
1 2 3 4 5 6 7 8 9 10 11 help (len )help (print )import mathhelp (math)help (list )help (dict )
八、实际应用示例 (一)数据处理示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 students = [ {'name' : 'Alice' , 'scores' : [85 , 90 , 78 ]}, {'name' : 'Bob' , 'scores' : [92 , 88 , 95 ]}, {'name' : 'Charlie' , 'scores' : [76 , 82 , 79 ]} ] for student in students: avg_score = sum (student['scores' ]) / len (student['scores' ]) student['average' ] = round (avg_score, 2 ) print (f"{student['name' ]} 的平均分: {student['average' ]} " ) best_student = max (students, key=lambda x: x['average' ]) print (f"最高平均分学生: {best_student['name' ]} ({best_student['average' ]} 分)" )all_passed = all (student['average' ] >= 60 for student in students) print (f"所有学生都及格: {all_passed} " )
(二)文本处理示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 text = "Python is a powerful programming language. Python is easy to learn." words = text.lower().replace('.' , '' ).replace(',' , '' ).split() print (f"总单词数: {len (words)} " )word_count = {} for word in words: word_count[word] = word_count.get(word, 0 ) + 1 sorted_words = sorted (word_count.items(), key=lambda x: x[1 ], reverse=True ) print ("单词频率统计:" )for word, count in sorted_words: print (f"{word} : {count} " ) long_words = list (filter (lambda x: len (x) > 5 , set (words))) print (f"长单词: {long_words} " )
(三)数据验证示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def validate_user_data (data ): """ 验证用户数据的完整性和有效性 """ required_fields = ['name' , 'age' , 'email' ] missing_fields = [field for field in required_fields if not hasattr (data, field) or not getattr (data, field)] if missing_fields: return False , f"缺少必填字段: {', ' .join(missing_fields)} " if not isinstance (data.age, int ) or data.age < 0 or data.age > 150 : return False , "年龄必须是0-150之间的整数" if '@' not in data.email or '.' not in data.email: return False , "邮箱格式不正确" return True , "验证通过" class UserData : def __init__ (self, name, age, email ): self .name = name self .age = age self .email = email user1 = UserData("Alice" , 25 , "alice@example.com" ) user2 = UserData("" , -5 , "invalid-email" ) print (validate_user_data(user1)) print (validate_user_data(user2))
九、性能优化建议 (一)选择合适的内置函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 numbers = [1 , 2 , 3 , 4 , 5 ] total = sum (numbers) total = 0 for num in numbers: total += num scores = [85 , 90 , 78 , 92 ] has_excellent = any (score >= 90 for score in scores) all_passed = all (score >= 60 for score in scores) has_excellent = False for score in scores: if score >= 90 : has_excellent = True break
(二)避免不必要的类型转换 1 2 3 4 5 6 7 numbers = [1 , 2 , 3 , 4 , 5 ] result = sum (numbers) numbers = ['1' , '2' , '3' , '4' , '5' ] result = sum (int (x) for x in numbers)
十、常见错误与注意事项 (一)类型错误 1 2 3 4 5 6 7 8 try : result = sum (['1' , '2' , '3' ]) except TypeError as e: print (f"错误: {e} " ) result = sum (int (x) for x in ['1' , '2' , '3' ]) print (f"正确结果: {result} " )
(二)空序列处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 empty_list = [] if empty_list: max_value = max (empty_list) else : max_value = None try : max_value = max (empty_list) except ValueError: max_value = None
(三)迭代器消耗 1 2 3 4 5 6 7 8 9 10 11 numbers = [1 , 2 , 3 , 4 , 5 ] filtered = filter (lambda x: x > 2 , numbers) print (list (filtered)) print (list (filtered)) filtered = list (filter (lambda x: x > 2 , numbers)) print (filtered) print (filtered)
总结 Python内置函数是Python编程的基础工具,掌握这些函数能够显著提高编程效率和代码质量。本文介绍了最常用的内置函数,包括数学运算、类型转换、序列操作、逻辑判断、输入输出和高级函数等类别。
在实际开发中,建议:
优先使用内置函数 :它们经过优化,性能更好
理解函数特性 :了解返回值类型和可能的异常
合理组合使用 :多个内置函数组合能解决复杂问题
注意类型安全 :使用isinstance()进行类型检查
处理边界情况 :考虑空序列、None值等特殊情况
通过系统学习和实践这些内置函数,能够写出更加Pythonic、高效和可读的代码。
参考资料
Python官方文档 - 内置函数:https://docs.python.org/zh-cn/3/library/functions.html 3
菜鸟教程 - Python内置函数:https://www.runoob.com/python/python-built-in-functions.html 1
知乎专栏 - Python内置函数详解:https://zhuanlan.zhihu.com/p/341323946 2