目录
-
- 引言
- 基础数据类型操作
-
- [1. len()](#1. len())
- [2. range()](#2. range())
- [3. enumerate()](#3. enumerate())
- [4. zip()](#4. zip())
- [5. sorted()](#5. sorted())
- 函数式编程工具
-
- [6. map()](#6. map())
- [7. filter()](#7. filter())
- [8. reduce()](#8. reduce())
- [9. any()](#9. any())
- [10. all()](#10. all())
- 输入输出与文件操作
-
- [11. open()](#11. open())
- [12. print()](#12. print())
- [13. input()](#13. input())
- [14. exec()](#14. exec())
- [15. eval()](#15. eval())
- 元编程与高级功能
-
- [16. dir()](#16. dir())
- [17. help()](#17. help())
- [18. type()](#18. type())
- [19. isinstance()](#19. isinstance())
- [20. hasattr()](#20. hasattr())
- [21. getattr()](#21. getattr())
- [22. setattr()](#22. setattr())
- [23. delattr()](#23. delattr())
- [24. globals()](#24. globals())
- [25. locals()](#25. locals())
- [26. vars()](#26. vars())
- [27. callable()](#27. callable())
- [28. compile()](#28. compile())
- [29. id()](#29. id())
- [30. hash()](#30. hash())
- 总结
- 🌈Python爬虫相关文章(推荐)

引言
Python内置函数是语言核心功能的直接体现,掌握它们能显著提升代码效率和可读性。本文系统梳理30个最常用的内置函数,涵盖数据类型操作、函数式编程、输入输出、元编程等核心领域。每个函数均包含语法解析、参数说明、典型案例及注意事项,助力开发者写出更Pythonic的代码。
基础数据类型操作
1. len()
语法 :len(iterable)
功能 :返回对象长度或元素个数
案例:
python
# 字符串长度
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])
功能 :生成整数序列
案例:
python
# 生成0-4序列
for i in range(5):
print(i) # 0,1,2,3,4
# 步长为2
even_numbers = list(range(0, 10, 2)) # [0,2,4,6,8]
3. enumerate()
语法 :enumerate(iterable, start=0)
功能 :同时获取索引和值
案例:
python
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)
功能 :合并多个可迭代对象
案例:
python
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)
功能 :返回排序后的新列表
案例:
python
# 按字符串长度排序
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words) # ['apple', 'cherry', 'banana']
函数式编程工具
6. map()
语法 :map(function, iterable)
功能 :对可迭代对象每个元素应用函数
案例:
python
# 平方计算
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16]
7. filter()
语法 :filter(function, iterable)
功能 :筛选符合条件的元素
案例:
python
# 过滤偶数
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])
功能 :对可迭代对象中的元素进行累积计算
案例:
python
from functools import reduce
# 计算乘积
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 24
9. any()
语法 :any(iterable)
功能 :检查是否至少有一个元素为真
案例:
python
# 检测用户权限
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)
功能 :检查是否所有元素都为真
案例:
python
# 验证表单数据
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)
功能 :文件操作
案例:
python
# 写入文件
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)
功能 :输出内容到控制台
案例:
python
# 格式化输出
name = "Alice"
age = 25
print(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])
功能 :获取用户输入
案例:
python
# 简单交互
username = input("Enter your name: ")
print(f"Welcome, {username}!")
14. exec()
语法 :exec(object[, globals[, locals]])
功能 :执行动态生成的代码
案例:
python
# 动态执行代码
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Bob")
"""
exec(code) # 输出: Hello, Bob!
15. eval()
语法 :eval(expression[, globals[, locals]])
功能 :执行表达式并返回结果
案例:
python
# 计算数学表达式
result = eval("2 + 3 * 4")
print(result) # 14
# 动态创建对象
cls_name = "int"
obj = eval(f"{cls_name}(10)")
print(obj) # 10
元编程与高级功能
16. dir()
语法 :dir([object])
功能 :查看对象属性和方法
案例:
python
# 查看列表方法
print(dir([])) # 包含append, count, index等方法
# 查看模块内容
import math
print(dir(math)) # 包含sqrt, pi等属性和函数
17. help()
语法 :help([object])
功能 :获取帮助文档
案例:
python
# 查看len函数的帮助
help(len)
# 查看列表的帮助
help(list)
18. type()
语法 :type(object)
功能 :获取对象类型
案例:
python
# 类型检查
print(type(10)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1,2,3])) # <class 'list'>
19. isinstance()
语法 :isinstance(object, classinfo)
功能 :检查对象是否为指定类型
案例:
python
# 类型验证
class MyClass:
pass
obj = MyClass()
print(isinstance(obj, MyClass)) # True
print(isinstance(10, int)) # True
20. hasattr()
语法 :hasattr(object, name)
功能 :检查对象是否有指定属性
案例:
python
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(hasattr(p, "name")) # True
print(hasattr(p, "age")) # False
21. getattr()
语法 :getattr(object, name[, default])
功能 :获取对象属性值
案例:
python
class Config:
debug = False
config = Config()
print(getattr(config, "debug")) # False
print(getattr(config, "timeout", 30)) # 30(属性不存在时返回默认值)
22. setattr()
语法 :setattr(object, name, value)
功能 :设置对象属性值
案例:
python
class User:
pass
user = User()
setattr(user, "name", "Alice")
setattr(user, "age", 25)
print(user.name, user.age) # Alice 25
23. delattr()
语法 :delattr(object, name)
功能 :删除对象属性
案例:
python
class Data:
value = 42
data = Data()
delattr(data, "value")
print(hasattr(data, "value")) # False
24. globals()
语法 :globals()
功能 :返回当前全局符号表
案例:
python
# 查看全局变量
print(globals()["__name__"]) # __main__
# 动态创建全局变量
globals()["new_var"] = "Hello"
print(new_var) # Hello
25. locals()
语法 :locals()
功能 :返回当前局部符号表
案例:
python
def example():
local_var = 42
print(locals())
example()
# 输出包含'local_var'的字典
26. vars()
语法 :vars([object])
功能 :返回对象属性字典
案例:
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(vars(p)) # {'x': 1, 'y': 2}
27. callable()
语法 :callable(object)
功能 :检查对象是否可调用
案例:
python
print(callable(len)) # True(函数对象)
print(callable(10)) # False(整数不可调用)
print(callable(lambda x: x)) # True(lambda表达式)
28. compile()
语法 :compile(source, filename, mode)
功能 :将源代码编译为代码对象
案例:
python
# 编译并执行代码
code_str = "print('Hello from compiled code')"
code_obj = compile(code_str, "<string>", "exec")
exec(code_obj) # 输出: Hello from compiled code
29. id()
语法 :id(object)
功能 :返回对象的内存地址
案例:
python
a = 10
b = a
print(id(a)) # 140735530235488
print(id(b)) # 140735530235488(相同值对象共享内存)
30. hash()
语法 :hash(object)
功能 :返回对象的哈希值
案例:
python
print(hash("hello")) # -7176065445015297706
print(hash(10)) # 10
总结
Python内置函数是语言核心竞争力的体现,合理使用能显著提升开发效率。建议掌握以下原则:
- 优先使用内置函数 :如用
len()
代替手动计数,用zip()
代替手动索引对齐 - 注意函数副作用 :如
sorted()
返回新列表,而list.sort()
原地排序 - 结合高级特性 :将
map()
与生成器表达式结合,filter()
与lambda结合使用 - 避免过度使用 :如
exec()
和eval()
存在安全风险,需谨慎处理输入
通过系统掌握这些内置函数,开发者能写出更简洁、高效、Pythonic的代码。建议结合官方文档持续学习,探索更多高级用法。