常用内置函数#
Python 提供了丰富的内置函数,无需导入即可使用。掌握这些函数可以大大提高编程效率。
类型相关函数#
type() 和 isinstance()#
# type() - 获取对象类型
print(type(10)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1, 2])) # <class 'list'>
# isinstance() - 检查对象类型(推荐)
print(isinstance(10, int)) # True
print(isinstance("hello", str)) # True
print(isinstance([1, 2], (list, tuple))) # True(检查多个类型)len()#
# 获取序列长度
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
print(len({"a": 1})) # 1
print(len((1, 2, 3))) # 3str(), int(), float(), bool()#
# 类型转换
str(123) # '123'
int("123") # 123
int(3.7) # 3(向下取整)
float("3.14") # 3.14
bool(1) # True
bool(0) # False
bool("") # False
bool("abc") # Truelist(), tuple(), dict(), set()#
# 创建容器
list("abc") # ['a', 'b', 'c']
tuple([1, 2, 3]) # (1, 2, 3)
dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}
set([1, 2, 2, 3]) # {1, 2, 3}数学函数#
abs()#
# 绝对值
abs(-5) # 5
abs(5) # 5
abs(-3.14) # 3.14round()#
# 四舍五入
round(3.14159) # 3
round(3.14159, 2) # 3.14(保留2位小数)
round(3.5) # 4
round(2.5) # 2(注意:Python的round使用"银行家舍入")min() 和 max()#
# 最小值
min(1, 2, 3) # 1
min([1, 2, 3]) # 1
min("abc", "def", key=len) # 'abc'(使用key函数)
# 最大值
max(1, 2, 3) # 3
max([1, 2, 3]) # 3
max("hello", "hi", key=len) # 'hello'sum()#
# 求和
sum([1, 2, 3, 4]) # 10
sum([1, 2, 3], 10) # 16(从10开始累加)
sum(range(5)) # 10(0+1+2+3+4)pow()#
# 幂运算
pow(2, 3) # 8(2的3次方)
pow(2, 3, 5) # 3(2的3次方对5取模)
2 ** 3 # 8(等价写法)divmod()#
# 返回商和余数
divmod(10, 3) # (3, 1)(10除以3,商3余1)
quotient, remainder = divmod(10, 3)序列操作函数#
sorted()#
# 排序(返回新列表)
numbers = [3, 1, 4, 1, 5]
sorted(numbers) # [1, 1, 3, 4, 5]
sorted(numbers, reverse=True) # [5, 4, 3, 1, 1]
# 使用key函数
words = ["apple", "banana", "cherry"]
sorted(words, key=len) # ['apple', 'banana', 'cherry'](按长度)
sorted(words, key=str.lower) # 按小写字母排序
# 对字典排序
d = {"b": 2, "a": 1, "c": 3}
sorted(d.items(), key=lambda x: x[1]) # [('a', 1), ('b', 2), ('c', 3)]reversed()#
# 反转序列(返回迭代器)
list(reversed([1, 2, 3])) # [3, 2, 1]
list(reversed("hello")) # ['o', 'l', 'l', 'e', 'h']
# 字符串反转
"hello"[::-1] # 'olleh'(切片方式)enumerate()#
# 同时获取索引和值
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 输出:
# 0: apple
# 1: banana
# 2: cherry
# 指定起始索引
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")zip()#
# 同时遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 转换为列表
list(zip(names, ages)) # [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
# 解包
names2, ages2 = zip(*zip(names, ages))range()#
# 生成数字序列
list(range(5)) # [0, 1, 2, 3, 4]
list(range(2, 5)) # [2, 3, 4]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]输入输出函数#
print()#
# 基本用法
print("Hello, World!")
# 多个参数
print("Hello", "World", "!") # Hello World !
# 指定分隔符
print("Hello", "World", sep="-") # Hello-World
# 指定结束符
print("Hello", end="")
print("World") # HelloWorld(不换行)
# 格式化输出
name = "Alice"
age = 30
print(f"{name} is {age} years old") # Alice is 30 years oldinput()#
# 获取用户输入
name = input("请输入你的名字: ")
print(f"你好, {name}!")
# 注意:input()返回字符串
age = input("请输入年龄: ")
age = int(age) # 需要转换类型对象操作函数#
id()#
# 获取对象的内存地址
x = [1, 2, 3]
print(id(x)) # 某个内存地址hash()#
# 获取对象的哈希值
hash("hello") # 某个整数
hash((1, 2, 3)) # 某个整数
# hash([1, 2, 3]) # 错误!列表不可哈希dir()#
# 获取对象的属性和方法列表
dir([]) # 列表的所有方法
dir(str) # 字符串的所有方法
dir(__builtins__) # 所有内置函数和异常vars() 和 dict#
# 获取对象的属性字典
class MyClass:
def __init__(self):
self.x = 1
self.y = 2
obj = MyClass()
print(vars(obj)) # {'x': 1, 'y': 2}
print(obj.__dict__) # {'x': 1, 'y': 2}hasattr(), getattr(), setattr()#
class MyClass:
def __init__(self):
self.x = 1
obj = MyClass()
# hasattr() - 检查是否有属性
print(hasattr(obj, "x")) # True
print(hasattr(obj, "y")) # False
# getattr() - 获取属性
print(getattr(obj, "x")) # 1
print(getattr(obj, "y", 0)) # 0(默认值)
# setattr() - 设置属性
setattr(obj, "y", 2)
print(obj.y) # 2函数式编程工具#
map()#
# 对序列的每个元素应用函数
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
# 多个序列
list(map(lambda x, y: x + y, [1, 2], [3, 4])) # [4, 6]filter()#
# 过滤序列
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# 过滤None值
values = [1, None, 2, None, 3]
filtered = list(filter(None, values)) # [1, 2, 3]reduce()#
# 累积计算(需要导入)
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers) # 24
# 带初始值
sum_with_init = reduce(lambda x, y: x + y, numbers, 10) # 20其他常用函数#
any() 和 all()#
# any() - 至少一个为True
any([False, False, True]) # True
any([False, False, False]) # False
# all() - 全部为True
all([True, True, True]) # True
all([True, False, True]) # Falseslice()#
# 创建切片对象
my_list = [0, 1, 2, 3, 4, 5]
s = slice(1, 4)
print(my_list[s]) # [1, 2, 3]iter() 和 next()#
# iter() - 获取迭代器
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
# next() - 获取下一个值
print(next(iterator, "默认值")) # 3
print(next(iterator, "默认值")) # 默认值(迭代器耗尽)open()#
# 打开文件
with open("file.txt", "r") as f:
content = f.read()eval() 和 exec()#
# eval() - 执行表达式(危险!)
result = eval("2 + 3") # 5
# exec() - 执行代码(危险!)
exec("x = 10")
print(x) # 10
# 注意:eval()和exec()存在安全风险,应谨慎使用函数分类总结#
类型检查和转换#
type(),isinstance(),str(),int(),float(),bool(),list(),tuple(),dict(),set()
数学运算#
abs(),round(),min(),max(),sum(),pow(),divmod()
序列操作#
len(),sorted(),reversed(),enumerate(),zip(),range()
输入输出#
print(),input()
对象操作#
id(),hash(),dir(),vars(),hasattr(),getattr(),setattr()
函数式编程#
map(),filter(),reduce()(需要导入functools)
逻辑判断#
any(),all()
使用建议#
- 优先使用内置函数,它们通常比自定义实现更快
- 理解函数的返回值类型(列表、迭代器等)
- 注意内存效率(生成器 vs 列表)
- 合理使用lambda和函数式编程工具
- 避免使用eval()和exec(),除非绝对必要
下一步#
恭喜!你已经掌握了 Python 的核心内容。可以继续学习:
- 常用第三方库(如 NumPy、Pandas、Matplotlib)
- Web 开发框架(如 Django、Flask)
- 数据科学和机器学习库
- 测试和调试技巧
- 代码优化和性能提升