Python(32)Python内置函数全解析:30个核心函数的语法、案例与最佳实践
目录
-
- 引言
- 基础数据类型操作
-
- 1. len()
- 2. range()
- 3. enumerate()
- 4. zip()
- 5. sorted()
- 函数式编程工具
-
- 6. map()
- 7. filter()
- 8. reduce()
- 9. any()
- 10. all()
- 输入输出与文件操作
-
- 11. open()
- 12. print()
- 13. input()
- 14. exec()
- 15. eval()
- 元编程与高级功能
-
- 16. dir()
- 17. help()
- 18. type()
- 19. isinstance()
- 20. hasattr()
- 21. getattr()
- 22. setattr()
- 23. delattr()
- 24. globals()
- 25. locals()
- 26. vars()
- 27. callable()
- 28. compile()
- 29. id()
- 30. hash()
- 总结
- 🌈Python爬虫相关文章(推荐)
引言
Python内置函数是语言核心功能的直接体现,掌握它们能显著提升代码效率和可读性。本文系统梳理30个最常用的内置函数,涵盖数据类型操作、函数式编程、输入输出、元编程等核心领域。每个函数均包含语法解析、参数说明、典型案例及注意事项,助力开发者写出更Pythonic的代码。
基础数据类型操作
1. len()
语法:len(iterable)
功能:返回对象长度或元素个数
案例:
# 字符串长度print(len(\"Hello World\")) # 11# 列表元素个数data = [1, 2, [3, 4]]print(len(data)) # 3# 字典键值对数量stats = {\"a\": 1, \"b\": 2}print(len(stats)) # 2
2. range()
语法:range(start, stop[, step])
功能:生成整数序列
案例:
# 生成0-4序列for i in range(5): print(i) # 0,1,2,3,4# 步长为2even_numbers = list(range(0, 10, 2)) # [0,2,4,6,8]
3. enumerate()
语法:enumerate(iterable, start=0)
功能:同时获取索引和值
案例:
fruits = [\"apple\", \"banana\", \"cherry\"]for index, value in enumerate(fruits, 1): print(f\"{index}: {value}\")# 1: apple# 2: banana# 3: cherry
4. zip()
语法:zip(*iterables)
功能:合并多个可迭代对象
案例:
names = [\"Alice\", \"Bob\"]ages = [25, 30]for name, age in zip(names, ages): print(f\"{name} is {age} years old\")# Alice is 25 years old# Bob is 30 years old
5. sorted()
语法:sorted(iterable, key=None, reverse=False)
功能:返回排序后的新列表
案例:
# 按字符串长度排序words = [\"apple\", \"banana\", \"cherry\"]sorted_words = sorted(words, key=len)print(sorted_words) # [\'apple\', \'cherry\', \'banana\']
函数式编程工具
6. map()
语法:map(function, iterable)
功能:对可迭代对象每个元素应用函数
案例:
# 平方计算numbers = [1, 2, 3, 4]squares = list(map(lambda x: x**2, numbers))print(squares) # [1, 4, 9, 16]
7. filter()
语法:filter(function, iterable)
功能:筛选符合条件的元素
案例:
# 过滤偶数numbers = [1, 2, 3, 4, 5, 6]evens = list(filter(lambda x: x % 2 == 0, numbers))print(evens) # [2, 4, 6]
8. reduce()
语法:reduce(function, iterable[, initializer])
功能:对可迭代对象中的元素进行累积计算
案例:
from functools import reduce# 计算乘积numbers = [1, 2, 3, 4]product = reduce(lambda x, y: x * y, numbers)print(product) # 24
9. any()
语法:any(iterable)
功能:检查是否至少有一个元素为真
案例:
# 检测用户权限permissions = [\"read\", \"write\"]if any(perm in permissions for perm in [\"delete\", \"execute\"]): print(\"Has required permission\")else: print(\"Permission denied\") # 输出
10. all()
语法:all(iterable)
功能:检查是否所有元素都为真
案例:
# 验证表单数据form_data = { \"username\": \"alice\", \"email\": \"alice@example.com\", \"age\": \"25\"}if all(form_data.values()): print(\"Form is valid\")else: print(\"Missing fields\")
输入输出与文件操作
11. open()
语法:open(file, mode=\'r\', encoding=None)
功能:文件操作
案例:
# 写入文件with open(\"data.txt\", \"w\", encoding=\"utf-8\") as f: f.write(\"Hello, World!\")# 读取文件with open(\"data.txt\", \"r\", encoding=\"utf-8\") as f: content = f.read() print(content) # Hello, World!
12. print()
语法:print(*objects, sep=\' \', end=\'\\n\', file=sys.stdout)
功能:输出内容到控制台
案例:
# 格式化输出name = \"Alice\"age = 25print(f\"Name: {name}, Age: {age}\") # Name: Alice, Age: 25# 重定向输出到文件with open(\"output.txt\", \"w\") as f: print(\"This will be written to file\", file=f)
13. input()
语法:input([prompt])
功能:获取用户输入
案例:
# 简单交互username = input(\"Enter your name: \")print(f\"Welcome, {username}!\")
14. exec()
语法:exec(object[, globals[, locals]])
功能:执行动态生成的代码
案例:
# 动态执行代码code = \"\"\"def greet(name): print(f\"Hello, {name}!\")greet(\"Bob\")\"\"\"exec(code) # 输出: Hello, Bob!
15. eval()
语法:eval(expression[, globals[, locals]])
功能:执行表达式并返回结果
案例:
# 计算数学表达式result = eval(\"2 + 3 * 4\")print(result) # 14# 动态创建对象cls_name = \"int\"obj = eval(f\"{cls_name}(10)\")print(obj) # 10
元编程与高级功能
16. dir()
语法:dir([object])
功能:查看对象属性和方法
案例:
# 查看列表方法print(dir([])) # 包含append, count, index等方法# 查看模块内容import mathprint(dir(math)) # 包含sqrt, pi等属性和函数
17. help()
语法:help([object])
功能:获取帮助文档
案例:
# 查看len函数的帮助help(len)# 查看列表的帮助help(list)
18. type()
语法:type(object)
功能:获取对象类型
案例:
# 类型检查print(type(10)) # print(type(\"hello\")) # print(type([1,2,3])) #
19. isinstance()
语法:isinstance(object, classinfo)
功能:检查对象是否为指定类型
案例:
# 类型验证class MyClass: passobj = MyClass()print(isinstance(obj, MyClass)) # Trueprint(isinstance(10, int)) # True
20. hasattr()
语法:hasattr(object, name)
功能:检查对象是否有指定属性
案例:
class Person: def __init__(self, name): self.name = namep = Person(\"Alice\")print(hasattr(p, \"name\")) # Trueprint(hasattr(p, \"age\")) # False
21. getattr()
语法:getattr(object, name[, default])
功能:获取对象属性值
案例:
class Config: debug = Falseconfig = Config()print(getattr(config, \"debug\")) # Falseprint(getattr(config, \"timeout\", 30)) # 30(属性不存在时返回默认值)
22. setattr()
语法:setattr(object, name, value)
功能:设置对象属性值
案例:
class User: passuser = User()setattr(user, \"name\", \"Alice\")setattr(user, \"age\", 25)print(user.name, user.age) # Alice 25
23. delattr()
语法:delattr(object, name)
功能:删除对象属性
案例:
class Data: value = 42data = Data()delattr(data, \"value\")print(hasattr(data, \"value\")) # False
24. globals()
语法:globals()
功能:返回当前全局符号表
案例:
# 查看全局变量print(globals()[\"__name__\"]) # __main__# 动态创建全局变量globals()[\"new_var\"] = \"Hello\"print(new_var) # Hello
25. locals()
语法:locals()
功能:返回当前局部符号表
案例:
def example(): local_var = 42 print(locals())example()# 输出包含\'local_var\'的字典
26. vars()
语法:vars([object])
功能:返回对象属性字典
案例:
class Point: def __init__(self, x, y): self.x = x self.y = yp = Point(1, 2)print(vars(p)) # {\'x\': 1, \'y\': 2}
27. callable()
语法:callable(object)
功能:检查对象是否可调用
案例:
print(callable(len)) # True(函数对象)print(callable(10)) # False(整数不可调用)print(callable(lambda x: x)) # True(lambda表达式)
28. compile()
语法:compile(source, filename, mode)
功能:将源代码编译为代码对象
案例:
# 编译并执行代码code_str = \"print(\'Hello from compiled code\')\"code_obj = compile(code_str, \"\", \"exec\")exec(code_obj) # 输出: Hello from compiled code
29. id()
语法:id(object)
功能:返回对象的内存地址
案例:
a = 10b = aprint(id(a)) # 140735530235488print(id(b)) # 140735530235488(相同值对象共享内存)
30. hash()
语法:hash(object)
功能:返回对象的哈希值
案例:
print(hash(\"hello\")) # -7176065445015297706print(hash(10)) # 10
总结
Python内置函数是语言核心竞争力的体现,合理使用能显著提升开发效率。建议掌握以下原则:
- 优先使用内置函数:如用
len()
代替手动计数,用zip()
代替手动索引对齐 - 注意函数副作用:如
sorted()
返回新列表,而list.sort()
原地排序 - 结合高级特性:将
map()
与生成器表达式结合,filter()
与lambda结合使用 - 避免过度使用:如
exec()
和eval()
存在安全风险,需谨慎处理输入
通过系统掌握这些内置函数,开发者能写出更简洁、高效、Pythonic的代码。建议结合官方文档持续学习,探索更多高级用法。