1 基础
1.1 数据类型
00.总结
a.说明
Python 的数据类型是动态类型的,变量不需要提前声明类型,可以存储不同类型的值。
Python 是强类型语言,类型检查在运行时进行,不支持隐式类型转换(除了数值类型间的自动转换)。
Python 中一切皆对象,每个数据类型都有对应的类和属性方法。
b.分类
数值类型:int、float、complex、bool
序列类型:str、list、tuple、range
映射类型:dict
集合类型:set、frozenset
其他类型:None、bytes、bytearray、memoryview
c.区别
可变类型:list、dict、set、bytearray,内容可以被修改
不可变类型:int、float、str、tuple、frozenset、bytes、None,内容不能被修改
d.总结
| 类型分类 | 可变类型 | 不可变类型 | 特点 |
|---------|---------|-----------|------|
| 数值类型 | | int, float, complex, bool | 支持数学运算 |
| 序列类型 | list | str, tuple, range | 有序存储 |
| 映射类型 | dict | | 键值对存储 |
| 集合类型 | set | frozenset | 无重复元素 |
| 其他类型 | bytearray | None, bytes, memoryview | 特殊用途 |
e.基本数据类型
| 类型 | 示例 | 描述 |
|-----|------|------|
| int | 42, -17, 0 | 整数,无精度限制 |
| float | 3.14, -0.5, 2.5e-3 | 浮点数,双精度 |
| complex | 3+4j, complex(1, 2) | 复数类型 |
| bool | True, False | 布尔值,int 的子类 |
f.容器类型
| 类型 | 示例 | 描述 |
|-----|------|------|
| str | "hello", 'Python' | 字符串,不可变 |
| list | [1, 2, 3], ['a', 'b'] | 列表,可变有序 |
| tuple | (1, 2), (a, b) | 元组,不可变有序 |
| dict | {'a': 1, 'b': 2} | 字典,键值对 |
| set | {1, 2, 3} | 集合,无重复 |
g.特殊类型
| 类型 | 示例 | 描述 |
|-----|------|------|
| None | None | 空值 |
| bytes | b"hello" | 字节序列 |
| bytearray | bytearray(5) | 可写字节序列 |
01.数值类型(Numeric types)
a.整型(int)
整型是 Python 中最基本的数值类型,可以表示任意大小的整数。
Python 3 中的 int 没有大小限制,只受内存限制。
-----------------------------------------------------------------------------------------------------
基本用法:
num = 42 # 正整数
negative = -17 # 负整数
zero = 0 # 零
big_num = 10**100 # 大整数,Python 可以处理
-----------------------------------------------------------------------------------------------------
进制表示:
decimal = 255 # 十进制
binary = 0b11111111 # 二进制
octal = 0o377 # 八进制
hexadecimal = 0xFF # 十六进制
-----------------------------------------------------------------------------------------------------
类型转换:
int("123") = 123 # 字符串转整数
int(3.14) = 3 # 浮点数转整数(截断)
int(True) = 1 # 布尔值转整数
-----------------------------------------------------------------------------------------------------
常用方法:
num.bit_length() # 返回二进制位数
num.to_bytes() # 转换为字节
int.from_bytes() # 从字节转换
b.浮点型(float)
浮点型用于表示带小数的数值,在 Python 中使用 IEEE 754 双精度标准。
-----------------------------------------------------------------------------------------------------
基本用法:
pi = 3.14159 # 小数形式
scientific = 1.23e-4 # 科学计数法
negative_float = -2.5 # 负浮点数
-----------------------------------------------------------------------------------------------------
特殊值:
positive_inf = float('inf') # 正无穷
negative_inf = float('-inf') # 负无穷
nan = float('nan') # 非数字(Not a Number)
-----------------------------------------------------------------------------------------------------
类型转换:
float("3.14") = 3.14 # 字符串转浮点数
float(42) = 42.0 # 整数转浮点数
-----------------------------------------------------------------------------------------------------
常用方法:
num.is_integer() # 判断是否为整数
num.as_integer_ratio() # 转换为分数形式
float.hex() # 十六进制表示
c.复数(complex)
复数类型用于表示数学中的复数,包含实部和虚部。
-----------------------------------------------------------------------------------------------------
基本用法:
c1 = 3 + 4j # 复数形式
c2 = complex(1, 2) # 使用 complex() 函数
c3 = 5j # 纯虚数
-----------------------------------------------------------------------------------------------------
属性访问:
c1.real # 实部 = 3.0
c1.imag # 虚部 = 4.0
c1.conjugate() # 共轭复数 = 3 - 4j
-----------------------------------------------------------------------------------------------------
运算:
(3 + 4j) + (1 + 2j) = 4 + 6j # 加法
(3 + 4j) * (1 + 2j) = -5 + 10j # 乘法
abs(3 + 4j) = 5.0 # 模长
d.布尔型(bool)
布尔型是整型的子类,只有两个值:True 和 False。
-----------------------------------------------------------------------------------------------------
基本用法:
is_active = True
is_empty = False
-----------------------------------------------------------------------------------------------------
类型转换:
bool(0) = False # 0 转 False
bool(1) = True # 非 0 转 True
bool("") = False # 空字符串转 False
bool("hello") = True # 非空字符串转 True
bool([]) = False # 空容器转 False
bool([1, 2]) = True # 非空容器转 True
-----------------------------------------------------------------------------------------------------
运算:
True and False = False
True or False = True
not True = False
-----------------------------------------------------------------------------------------------------
整数转换:
int(True) = 1 # True 转 1
int(False) = 0 # False 转 0
02.序列类型(Sequence types)
a.字符串(str)
字符串是字符的序列,用于表示文本数据。Python 中字符串是不可变的。
-----------------------------------------------------------------------------------------------------
创建字符串:
s1 = 'hello' # 单引号
s2 = "world" # 双引号
s3 = '''多行字符串''' # 三单引号
s4 = """多行字符串""" # 三双引号
-----------------------------------------------------------------------------------------------------
转义字符:
s = "Hello\nWorld" # \n 换行
s = "Hello\\World" # \\ 反斜杠
s = "Hello\"World\"" # \" 双引号
s = "Hello\'World\'" # \' 单引号
s = "Hello\tWorld" # \t 制表符
-----------------------------------------------------------------------------------------------------
原始字符串:
path = r"C:\Users\name" # 原始字符串,不转义
-----------------------------------------------------------------------------------------------------
字符串格式化:
name = "Alice"
age = 25
message = f"{name} is {age} years old" # f-string
message = "{0} is {1} years old".format(name, age) # format()
message = "%s is %d years old" % (name, age) # % 格式化
-----------------------------------------------------------------------------------------------------
常用方法:
s.upper() # 转大写
s.lower() # 转小写
s.strip() # 去除首尾空白
s.split(',') # 分割字符串
s.join(['a', 'b']) # 连接字符串
s.replace('old', 'new') # 替换
s.find('pattern') # 查找
s.count('char') # 计数
s.startswith('prefix') # 判断开头
s.endswith('suffix') # 判断结尾
b.列表(list)
列表是有序的可变序列,可以包含任意类型的元素。
-----------------------------------------------------------------------------------------------------
创建列表:
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []
nested = [[1, 2], [3, 4]]
-----------------------------------------------------------------------------------------------------
创建列表的方法:
list1 = list() # 空列表
list2 = list("hello") # 从字符串 ['h', 'e', 'l', 'l', 'o']
list3 = list(range(10)) # 从 range [0, 1, 2, ..., 9]
-----------------------------------------------------------------------------------------------------
访问和修改:
lst = [1, 2, 3, 4, 5]
first = lst[0] # 访问第一个元素
last = lst[-1] # 访问最后一个元素
lst[1] = 20 # 修改元素
lst[2:4] = [30, 40] # 修改切片
-----------------------------------------------------------------------------------------------------
列表操作:
lst.append(6) # 追加元素
lst.insert(0, 0) # 插入元素
lst.extend([7, 8]) # 扩展列表
lst.remove(3) # 删除指定值
lst.pop() # 删除最后一个元素
lst.pop(0) # 删除指定索引
lst.sort() # 排序
lst.reverse() # 反转
lst.index(3) # 查找索引
lst.count(3) # 计数
lst.clear() # 清空列表
-----------------------------------------------------------------------------------------------------
列表推导式:
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, ..., 81]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
c.元组(tuple)
元组是有序的不可变序列,一旦创建就不能修改。
-----------------------------------------------------------------------------------------------------
创建元组:
tup1 = (1, 2, 3) # 元组
tup2 = 1, 2, 3 # 省略括号
tup3 = (1,) # 单元素元组(注意逗号)
tup4 = () # 空元组
tup5 = tuple() # 空元组
-----------------------------------------------------------------------------------------------------
创建元组的方法:
tup1 = tuple([1, 2, 3]) # 从列表
tup2 = tuple("hello") # 从字符串 ('h', 'e', 'l', 'l', 'o')
tup3 = tuple(range(5)) # 从 range (0, 1, 2, 3, 4)
-----------------------------------------------------------------------------------------------------
访问元素:
tup = (1, 2, 3, 4, 5)
first = tup[0] # 访问第一个元素
last = tup[-1] # 访问最后一个元素
subset = tup[1:3] # 切片 (2, 3)
-----------------------------------------------------------------------------------------------------
元组操作:
tup1 + tup2 # 拼接元组
tup * 3 # 重复元组
len(tup) # 长度
tup.count(3) # 计数
tup.index(3) # 查找索引
3 in tup # 成员测试
-----------------------------------------------------------------------------------------------------
元组解包:
point = (3, 4)
x, y = point # x=3, y=4
-----------------------------------------------------------------------------------------------------
命名元组:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4) # p.x=3, p.y=4
03.映射类型(Mapping types)
a.字典(dict)
字典是键值对的集合,键必须是可哈希的类型,值可以是任意类型。
-----------------------------------------------------------------------------------------------------
创建字典:
d1 = {'a': 1, 'b': 2} # 字面量
d2 = dict(a=1, b=2) # dict() 函数
d3 = {} # 空字典
d4 = dict([('a', 1), ('b', 2)])# 从列表创建
-----------------------------------------------------------------------------------------------------
访问和修改:
d = {'a': 1, 'b': 2}
value = d['a'] # 访问键 'a' 的值
d['c'] = 3 # 添加新键值对
d['a'] = 10 # 修改键 'a' 的值
del d['b'] # 删除键值对
-----------------------------------------------------------------------------------------------------
字典方法:
d.get('key', default) # 安全访问
d.keys() # 所有键
d.values() # 所有值
d.items() # 所有键值对
d.update({'d': 4}) # 更新字典
d.pop('key') # 弹出指定键
d.popitem() # 弹出任意键值对
d.clear() # 清空字典
d.copy() # 复制字典
len(d) # 字典长度
'key' in d # 检查键是否存在
-----------------------------------------------------------------------------------------------------
字典推导式:
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
even_squares = {x: x**2 for x in range(10) if x % 2 == 0} # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
04.集合类型(Set types)
a.集合(set)
集合是无序的不重复元素集合,用于去重和集合运算。
-----------------------------------------------------------------------------------------------------
创建集合:
s1 = {1, 2, 3} # 字面量
s2 = set() # 空集合
s3 = set([1, 2, 3, 2, 1]) # 从列表创建(自动去重)
s4 = set("hello") # 从字符串创建 {'h', 'e', 'l', 'o'}
-----------------------------------------------------------------------------------------------------
集合操作:
s.add(4) # 添加元素
s.remove(1) # 删除元素(不存在则报错)
s.discard(1) # 删除元素(不存在不报错)
s.pop() # 删除任意元素
s.clear() # 清空集合
-----------------------------------------------------------------------------------------------------
集合运算:
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 | s2 # 并集 {1, 2, 3, 4, 5}
s1 & s2 # 交集 {3}
s1 - s2 # 差集 {1, 2}
s1 ^ s2 # 对称差集 {1, 2, 4, 5}
s1.issubset(s2) # 判断子集
s1.issuperset(s2) # 判断超集
s1.isdisjoint(s2) # 判断不相交
-----------------------------------------------------------------------------------------------------
集合方法:
len(s) # 集合长度
3 in s # 成员测试
s.update({4, 5}) # 更新集合
s.intersection_update({3, 4}) # 交集更新
s.difference_update({1, 2}) # 差集更新
s.symmetric_difference_update({3, 4}) # 对称差集更新
-----------------------------------------------------------------------------------------------------
集合推导式:
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
even_squares = {x**2 for x in range(10) if x % 2 == 0} # {0, 4, 16, 36, 64}
b.冻结集合(frozenset)
冻结集合是不可变的集合,创建后不能修改。
-----------------------------------------------------------------------------------------------------
创建冻结集合:
fs1 = frozenset({1, 2, 3})
fs2 = frozenset([1, 2, 3, 2, 1])
fs3 = frozenset("hello")
-----------------------------------------------------------------------------------------------------
冻结集合支持所有集合的只读操作:
fs1 | fs2 # 并集
fs1 & fs2 # 交集
fs1 - fs2 # 差集
fs1 ^ fs2 # 对称差集
-----------------------------------------------------------------------------------------------------
可以用作字典的键:
d = {frozenset({1, 2}): "value"}
05.其他类型
a.None 类型
None 表示空值或无值,是一个特殊的单例对象。
-----------------------------------------------------------------------------------------------------
用法:
def func(param=None):
if param is None:
print("参数为空")
-----------------------------------------------------------------------------------------------------
检查 None:
if value is None: # 推荐
if value is not None:
-----------------------------------------------------------------------------------------------------
注意:不要使用 == 比较None,应该使用 is
b.字节类型(bytes)
字节类型用于表示二进制数据,是不可变的字节序列。
-----------------------------------------------------------------------------------------------------
创建字节:
b1 = b"hello" # 字节字面量
b2 = bytes("hello", 'utf-8') # 从字符串创建
b3 = bytes([104, 101, 108, 108, 111]) # 从字节列表创建
b4 = b''.join([b'h', b'e']) # 拼接
-----------------------------------------------------------------------------------------------------
字节操作:
b1[0] # 访问单个字节
len(b1) # 长度
b1 + b2 # 拼接
b1 * 3 # 重复
b"hello" in b1 # 子串查找
-----------------------------------------------------------------------------------------------------
转换:
b1.decode('utf-8') # 字节转字符串
"hello".encode('utf-8') # 字符串转字节
list(b1) # 转换为字节列表
c.字节数组(bytearray)
字节数组是可变的字节序列,可以修改其中的字节。
-----------------------------------------------------------------------------------------------------
创建字节数组:
ba1 = bytearray(b"hello")
ba2 = bytearray([104, 101, 108, 108, 111])
ba3 = bytearray(5) # 创建指定长度的空字节数组
-----------------------------------------------------------------------------------------------------
修改操作:
ba1[0] = 72 # 修改第一个字节
ba1.append(33) # 追加字节
ba1.extend(b" world") # 扩展
ba1.remove(104) # 删除指定字节
ba1.pop() # 删除最后一个字节
-----------------------------------------------------------------------------------------------------
转换:
ba1.decode('utf-8') # 转换为字符串
bytes(ba1) # 转换为不可变字节
06.代码示例
# 数值类型示例
def numeric_types_demo():
# 整型
age = 25
big_number = 10**100
print(f"年龄: {age}, 大数位数: {big_number.bit_length()}")
# 浮点型
pi = 3.14159
print(f"π = {pi}, 是否为整数: {pi.is_integer()}")
# 复数
complex_num = 3 + 4j
print(f"复数: {complex_num}, 模长: {abs(complex_num)}")
# 布尔型
is_active = True
print(f"布尔值: {is_active}, 转整数: {int(is_active)}")
# 序列类型示例
def sequence_types_demo():
# 字符串
name = "Python"
message = f"Hello, {name}!"
print(f"字符串: {message}, 长度: {len(message)}")
# 列表
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(f"列表: {numbers}, 最大值: {max(numbers)}")
# 元组
point = (3, 4)
x, y = point
print(f"坐标: ({x}, {y}), 距离原点: {(x**2 + y**2)**0.5}")
# 映射类型示例
def mapping_types_demo():
student = {
'name': 'Alice',
'age': 20,
'grades': [90, 85, 95]
}
print(f"学生信息: {student}")
print(f"平均分: {sum(student['grades']) / len(student['grades'])}")
# 集合类型示例
def set_types_demo():
# 集合去重
scores = [85, 90, 85, 95, 90]
unique_scores = set(scores)
print(f"原始分数: {scores}")
print(f"不重复分数: {unique_scores}")
# 集合运算
math_students = {"Alice", "Bob", "Charlie"}
physics_students = {"Charlie", "David", "Eve"}
both_subjects = math_students & physics_students
print(f"同时学两门课的学生: {both_subjects}")
# 特殊类型示例
def special_types_demo():
# None 类型
def greet(name=None):
if name is None:
return "Hello, Stranger!"
return f"Hello, {name}!"
print(greet())
print(greet("Alice"))
# 字节类型
data = b"Hello, Python!"
print(f"字节: {data}")
print(f"解码后: {data.decode('utf-8')}")
# 字节数组
mutable_data = bytearray(b"Hello")
mutable_data[0] = 72 # 'H' 的 ASCII 码
print(f"修改后: {mutable_data.decode('utf-8')}")
if __name__ == "__main__":
numeric_types_demo()
sequence_types_demo()
mapping_types_demo()
set_types_demo()
special_types_demo()
1.2 类型转换
00.对比
a.总结
Python 是动态类型语言,变量的类型在运行时确定,类型转换分为隐式和显式两种。
隐式转换主要由 Python 解释器自动完成,通常在算术运算和布尔运算中发生。
显式转换需要开发者使用内置函数明确指定目标类型。
b.汇总
| 转换方式 | 方法 | 描述 | 示例 |
|---------|------|------|------|
| 隐式转换 | 自动进行 | Python 解释器自动处理 | 1 + 2.5 = 3.5 |
| 显式转换 | int() | 转换为整数 | int("123") = 123 |
| 显式转换 | float() | 转换为浮点数 | float("3.14") = 3.14 |
| 显式转换 | str() | 转换为字符串 | str(42) = "42" |
| 显式转换 | bool() | 转换为布尔值 | bool(0) = False |
| 显式转换 | list() | 转换为列表 | list("abc") = ['a', 'b', 'c'] |
| 显式转换 | tuple() | 转换为元组 | tuple([1,2]) = (1,2) |
| 显式转换 | set() | 转换为集合 | set([1,2,2]) = {1,2} |
| 显式转换 | dict() | 转换为字典 | dict([('a',1)]) = {'a':1} |
| 显式转换 | bytes() | 转换为字节 | bytes("hello","utf8") |
01.隐式类型转换
a.数值类型间的转换
Python 在数值运算中会自动将较小的类型转换为较大的类型,避免精度丢失。
-----------------------------------------------------------------------------------------------------
转换规则:
bool → int → float → complex
-----------------------------------------------------------------------------------------------------
示例:
# bool 转换为 int
result = True + 5 # 1 + 5 = 6
result = False + 10 # 0 + 10 = 10
# int 转换为 float
result = 3 + 4.5 # 3.0 + 4.5 = 7.5
result = 10 / 3 # 10.0 / 3.0 = 3.333...
# 所有数值类型转换到 complex
result = (1 + 2j) + 3 # (1+2j) + (3+0j) = (4+2j)
result = 5j * 2 # (0+5j) * (2+0j) = (0+10j)
b.布尔运算中的转换
在条件判断中,Python 会自动将各种类型转换为布尔值。
-----------------------------------------------------------------------------------------------------
转换规则:
以下值转换为 False:
- False
- None
- 数值 0(0, 0.0, 0j)
- 空序列('', (), [], set(), frozenset(), range(0))
- 空映射({})
-----------------------------------------------------------------------------------------------------
其他值都转换为 True。
示例:
if 0: # False,不执行
pass
if "": # False,不执行
pass
if "hello": # True,执行
pass
if [1, 2]: # True,执行
pass
if None: # False,不执行
pass
c.字符串格式化中的转换
字符串格式化时会自动调用类型的 __str__ 方法。
-----------------------------------------------------------------------------------------------------
示例:
age = 25
name = "Alice"
message = f"{name} is {age} years old" # 自动转换为字符串
02.显式类型转换
a.基本类型转换
使用内置函数进行显式类型转换:
# 转换为整数 int()
int("123") = 123 # 字符串转整数
int(3.14) = 3 # 浮点数转整数(截断)
int(True) = 1 # 布尔值转整数
int(False) = 0 # 布尔值转整数
# 转换为浮点数 float()
float("3.14") = 3.14 # 字符串转浮点数
float(42) = 42.0 # 整数转浮点数
float(True) = 1.0 # 布尔值转浮点数
# 转换为字符串 str()
str(123) = "123" # 整数转字符串
str(3.14) = "3.14" # 浮点数转字符串
str(True) = "True" # 布尔值转字符串
str([1, 2, 3]) = "[1, 2, 3]" # 列表转字符串
# 转换为布尔值 bool()
bool(0) = False # 0 转 False
bool(1) = True # 非 0 转 True
bool("") = False # 空字符串转 False
bool("hello") = True # 非空字符串转 True
bool([]) = False # 空列表转 False
bool([1, 2]) = True # 非空列表转 True
bool(None) = False # None 转 False
b.复数转换
complex(real, imag) 用于创建复数:
complex(3, 4) = (3+4j) # 创建复数
complex(3) = (3+0j) # 只有实部
complex() = 0j # 默认为 0
-----------------------------------------------------------------------------------------------------
从其他类型转换:
complex("3+4j") = (3+4j) # 字符串转复数
complex(3.14) = (3.14+0j) # 数值转复数
03.使用内置函数进行类型转换
a.序列类型转换
# 字符串转列表
list("hello") = ['h', 'e', 'l', 'l', 'o']
list(range(5)) = [0, 1, 2, 3, 4]
# 字符串转元组
tuple("abc") = ('a', 'b', 'c')
tuple([1, 2, 3]) = (1, 2, 3)
# 字符串转集合(自动去重)
set("hello") = {'h', 'e', 'l', 'o'}
set([1, 2, 2, 3]) = {1, 2, 3}
# 列表转字符串
''.join(['a', 'b', 'c']) = "abc"
','.join(['1', '2', '3']) = "1,2,3"
b.映射类型转换
# 字典转换
dict([('a', 1), ('b', 2)]) = {'a': 1, 'b': 2}
dict(a=1, b=2) = {'a': 1, 'b': 2}
# 字典键和值的转换
list(d.keys()) # 字典键转列表
list(d.values()) # 字典值转列表
list(d.items()) # 字典项转列表
c.字节类型转换
# 字符串转字节
bytes("hello", 'utf-8') = b'hello'
"hello".encode('utf-8') = b'hello'
# 字节转字符串
b'hello'.decode('utf-8') = 'hello'
str(b'hello', 'utf-8') = 'hello'
# 字节数组转换
bytearray(b'hello') = bytearray(b'hello')
bytearray("hello", 'utf-8') = bytearray(b'hello')
04.字符串转换
a.基础字符串转换
# 各种类型转字符串
str(123) = "123"
str(3.14) = "3.14"
str(True) = "True"
str([1, 2, 3]) = "[1, 2, 3]"
str({'a': 1}) = "{'a': 1}"
str((1, 2)) = "(1, 2)"
str({1, 2, 3}) = "{1, 2, 3}"
b.格式化字符串
# f-string(Python 3.6+)
name = "Alice"
age = 25
f"{name} is {age} years old" = "Alice is 25 years old"
# format() 方法
"{0} is {1} years old".format(name, age) = "Alice is 25 years old"
"{name} is {age} years old".format(name=name, age=age)
# % 格式化
"%s is %d years old" % (name, age) = "Alice is 25 years old"
# 格式化数字
f"{3.14159:.2f}" = "3.14" # 保留2位小数
f"{42:>5}" = " 42" # 右对齐,宽度5
f"{42:<5}" = "42 " # 左对齐,宽度5
f"{42:^5}" = " 42 " # 居中对齐,宽度5
c.字符串解析转换
# 从字符串解析数值
int("42") = 42
float("3.14") = 3.14
complex("3+4j") = (3+4j)
# 进制转换
int("1010", 2) = 10 # 二进制转十进制
int("FF", 16) = 255 # 十六进制转十进制
int("377", 8) = 255 # 八进制转十进制
# 布尔值解析
bool("True") = True
bool("False") = True # 注意:非空字符串都为 True
05.集合类型转换
a.容器间转换
# 列表转其他类型
my_list = [1, 2, 3]
tuple(my_list) = (1, 2, 3) # 转元组
set(my_list) = {1, 2, 3} # 转集合(自动去重)
frozenset(my_list) = frozenset({1, 2, 3}) # 转冻结集合
# 元组转其他类型
my_tuple = (1, 2, 3)
list(my_tuple) = [1, 2, 3] # 转列表
set(my_tuple) = {1, 2, 3} # 转集合
# 集合转其他类型
my_set = {1, 2, 3}
list(my_set) = [1, 2, 3] # 转列表(顺序可能不同)
tuple(my_set) = (1, 2, 3) # 转元组(顺序可能不同)
b.字符串与列表的相互转换
# 字符串转字符列表
list("hello") = ['h', 'e', 'l', 'l', 'o']
# 字符串转单词列表
"hello world python".split() = ['hello', 'world', 'python']
"a,b,c".split(',') = ['a', 'b', 'c']
# 列表转字符串
['h', 'e', 'l', 'l', 'o'] + "" = "hello"
"-".join(['a', 'b', 'c']) = "a-b-c"
c.字典与其他类型的转换
# 字典转列表
my_dict = {'a': 1, 'b': 2}
list(my_dict.keys()) = ['a', 'b'] # 键列表
list(my_dict.values()) = [1, 2] # 值列表
list(my_dict.items()) = [('a', 1), ('b', 2)] # 键值对列表
# 列表转字典
[('a', 1), ('b', 2)] 转 {'a': 1, 'b': 2} # 使用 dict()
['a', 'b'] 和 [1, 2] 转 {'a': 1, 'b': 2} # 使用 zip() 和 dict()
06.代码示例
# 隐式类型转换示例
def implicit_conversion_demo():
# 数值类型间的隐式转换
result1 = True + 5 # 1 + 5 = 6
result2 = 3 + 4.5 # 3.0 + 4.5 = 7.5
result3 = (1 + 2j) + 3 # (1+2j) + (3+0j) = (4+2j)
print(f"True + 5 = {result1}")
print(f"3 + 4.5 = {result2}")
print(f"(1+2j) + 3 = {result3}")
# 布尔运算中的隐式转换
if 0: # False,不执行
print("这不会打印")
if "hello": # True,执行
print("这会打印")
# 列表的隐式转换
empty_list = []
if empty_list: # False,不执行
print("空列表")
# 显式类型转换示例
def explicit_conversion_demo():
# 基本类型转换
text_num = "123"
num = int(text_num) # 转换为整数
float_num = float("3.14") # 转换为浮点数
text = str(42) # 转换为字符串
boolean = bool(0) # 转换为布尔值
print(f"字符串 '123' 转整数: {num}")
print(f"字符串 '3.14' 转浮点数: {float_num}")
print(f"整数 42 转字符串: '{text}'")
print(f"整数 0 转布尔值: {boolean}")
# 容器类型转换示例
def container_conversion_demo():
# 序列类型转换
text = "hello"
chars = list(text) # 转换为字符列表
chars_tuple = tuple(text) # 转换为字符元组
chars_set = set(text) # 转换为字符集合(去重)
print(f"字符串转字符列表: {chars}")
print(f"字符串转字符元组: {chars_tuple}")
print(f"字符串转字符集合: {chars_set}")
# 集合间转换
numbers = [1, 2, 2, 3, 4, 4]
unique_numbers = set(numbers) # 去重
unique_tuple = tuple(unique_numbers) # 转元组
unique_list = list(unique_numbers) # 转列表
print(f"原始列表: {numbers}")
print(f"去重后集合: {unique_numbers}")
print(f"去重后元组: {unique_tuple}")
# 字符串格式化示例
def string_formatting_demo():
name = "Alice"
age = 25
score = 89.5
# f-string 格式化
message1 = f"{name} is {age} years old"
message2 = f"Score: {score:.1f}" # 保留1位小数
# format() 方法
message3 = "{0} scored {1:.1f} points".format(name, score)
# 对齐格式化
message4 = f"{name:>10} | {age:<5} | {score:^7.1f}"
print(f"f-string: {message1}")
print(f"保留小数: {message2}")
print(f"format方法: {message3}")
print(f"对齐格式:")
print(f" {message4}")
# 进制转换示例
def base_conversion_demo():
# 十进制转其他进制
decimal_num = 255
binary = bin(decimal_num) # 0b11111111
octal = oct(decimal_num) # 0o377
hexadec = hex(decimal_num) # 0xff
# 其他进制转十进制
binary_to_dec = int("11111111", 2) # 255
octal_to_dec = int("377", 8) # 255
hex_to_dec = int("ff", 16) # 255
print(f"十进制 {decimal_num}:")
print(f" 二进制: {binary}")
print(f" 八进制: {octal}")
print(f" 十六进制: {hexadec}")
print(f"二进制 '11111111' 转十进制: {binary_to_dec}")
print(f"八进制 '377' 转十进制: {octal_to_dec}")
print(f"十六进制 'ff' 转十进制: {hex_to_dec}")
# 字典转换示例
def dict_conversion_demo():
# 键值对列表转字典
pairs = [('name', 'Alice'), ('age', 25), ('city', 'Beijing')]
student_dict = dict(pairs)
# 使用 zip 创建字典
keys = ['name', 'age', 'city']
values = ['Bob', 30, 'Shanghai']
another_dict = dict(zip(keys, values))
# 字典转列表
dict_keys = list(student_dict.keys())
dict_values = list(student_dict.values())
dict_items = list(student_dict.items())
print(f"字典: {student_dict}")
print(f"字典键: {dict_keys}")
print(f"字典值: {dict_values}")
print(f"字典项: {dict_items}")
print(f"另一个字典: {another_dict}")
# 综合转换示例
def comprehensive_conversion_demo():
# 复杂数据转换
data = "1,2,3,4,5"
numbers = [int(x) for x in data.split(',')] # 字符串分割转整数列表
numbers_tuple = tuple(numbers) # 转元组
numbers_squared = [x**2 for x in numbers] # 计算平方
numbers_set = set(numbers_squared) # 转集合去重
# 转换为字典
num_dict = {str(x): x**2 for x in numbers} # 数字字符串为键,平方为值
print(f"原始字符串: '{data}'")
print(f"整数列表: {numbers}")
print(f"整数元组: {numbers_tuple}")
print(f"平方列表: {numbers_squared}")
print(f"平方集合: {numbers_set}")
print(f"数字字典: {num_dict}")
if __name__ == "__main__":
print("=== 隐式类型转换 ===")
implicit_conversion_demo()
print("\n=== 显式类型转换 ===")
explicit_conversion_demo()
print("\n=== 容器类型转换 ===")
container_conversion_demo()
print("\n=== 字符串格式化 ===")
string_formatting_demo()
print("\n=== 进制转换 ===")
base_conversion_demo()
print("\n=== 字典转换 ===")
dict_conversion_demo()
print("\n=== 综合转换 ===")
comprehensive_conversion_demo()
1.3 变量和常量
01.变量
a.变量定义和赋值
Python 是动态类型语言,变量不需要提前声明类型,直接赋值即可创建变量。
变量名指向内存中的对象,同一个变量可以指向不同类型的对象。
-----------------------------------------------------------------------------------------------------
基本赋值:
name = "Alice" # 字符串类型
age = 25 # 整数类型
height = 1.75 # 浮点数类型
is_student = True # 布尔类型
scores = [90, 85, 95] # 列表类型
-----------------------------------------------------------------------------------------------------
变量重新赋值:
age = 26 # 修改值
age = "twenty-six" # 修改类型
age = 26.0 # 再次修改类型
-----------------------------------------------------------------------------------------------------
变量存储的是对象的引用:
a = [1, 2, 3]
b = a # b 和 a 指向同一个列表对象
b.append(4) # 修改列表
print(a) # [1, 2, 3, 4] - a 也被修改
-----------------------------------------------------------------------------------------------------
查看变量类型:
type(age) # 查看变量类型
isinstance(age, int) # 判断是否为指定类型
-----------------------------------------------------------------------------------------------------
查看变量内存地址:
id(a) # 查看对象的内存地址
id(b) # 如果 a 和 b 指向同一对象,地址相同
b.变量命名规则
命名规则:
1. 变量名必须以字母或下划线开头
2. 变量名只能包含字母、数字和下划线
3. 变量名区分大小写
4. 不能使用 Python 关键字
-----------------------------------------------------------------------------------------------------
有效命名:
name = "Alice"
user_name = "bob123"
_private_var = 42 # 下划线开头表示私有变量
camalCase = "value" # 驼峰命名法
-----------------------------------------------------------------------------------------------------
无效命名:
2name = "error" # 不能以数字开头
user-name = "error" # 不能包含连字符
class = "error" # 不能使用关键字
user name = "error" # 不能包含空格
-----------------------------------------------------------------------------------------------------
Python 关键字(部分):
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
-----------------------------------------------------------------------------------------------------
命名约定:
变量名和函数名:使用小写字母和下划线(snake_case)
类名:使用大驼峰命名法(PascalCase)
常量:使用大写字母和下划线(UPPER_CASE)
私有变量:以下划线开头(_private_var)
c.多重赋值
Python 支持多种多重赋值方式,可以同时为多个变量赋值。
-----------------------------------------------------------------------------------------------------
基本多重赋值:
a, b, c = 1, 2, 3 # 同时为三个变量赋值
x, y = 10, 20
-----------------------------------------------------------------------------------------------------
交换变量值:
x, y = y, x # 交换 x 和 y 的值
-----------------------------------------------------------------------------------------------------
解包赋值:
point = (3, 4)
x, y = point # 元组解包
-----------------------------------------------------------------------------------------------------
data = [1, 2, 3, 4, 5]
first, second, *rest = data # *rest 接收剩余元素
# first=1, second=2, rest=[3, 4, 5]
first, *middle, last = data
# first=1, middle=[2, 3, 4], last=5
-----------------------------------------------------------------------------------------------------
函数返回值多重赋值:
def get_coordinates():
return 10, 20
x, y = get_coordinates()
-----------------------------------------------------------------------------------------------------
星号表达式:
numbers = [1, 2, 3, 4, 5]
a, *b, c = numbers # a=1, b=[2, 3, 4], c=5
-----------------------------------------------------------------------------------------------------
链式赋值:
x = y = z = 0 # x、y、z 都指向同一个对象
-----------------------------------------------------------------------------------------------------
增量赋值:
x = 10
x += 5 # x = x + 5 = 15
x -= 3 # x = x - 3 = 12
x *= 2 # x = x * 2 = 24
x /= 3 # x = x / 3 = 8.0
-----------------------------------------------------------------------------------------------------
其他增量操作符:
%= // %= **= <<= >>= &= ^= |=
d.变量作用域
Python 变量作用域分为四种:LEGB 规则(Local → Enclosing → Global → Built-in)
1.局部作用域(Local)
函数内部定义的变量
2.嵌套作用域(Enclosing)
嵌套函数中外层函数的变量
3.全局作用域(Global)
模块级别定义的变量
4.内置作用域(Built-in)
Python 内置的变量和函数
-----------------------------------------------------------------------------------------------------
示例:
global_var = "全局变量" # 全局变量
def outer_function():
enclosing_var = "嵌套变量" # 嵌套作用域
def inner_function():
local_var = "局部变量" # 局部变量
print(local_var) # 可以访问局部变量
print(enclosing_var) # 可以访问嵌套变量
print(global_var) # 可以访问全局变量
inner_function()
# print(local_var) # 错误:无法访问局部变量
# 访问和修改不同作用域的变量:
count = 0 # 全局变量
def increment():
global count # 声明使用全局变量
count += 1 # 修改全局变量
def outer():
x = 10 # 嵌套作用域变量
def inner():
nonlocal x # 声明使用嵌套作用域变量
x += 5 # 修改嵌套作用域变量
inner()
return x # 返回修改后的值
# 变量查找顺序(LEGB):
x = "全局"
def test():
x = "局部"
print(x) # 输出"局部"(找到局部变量就停止查找)
del 函数:
def example():
x = "局部变量"
del x # 删除局部变量
# print(x) # NameError: name 'x' is not defined
-----------------------------------------------------------------------------------------------------
变量生命周期:
局部变量:函数调用时创建,函数结束时销毁
全局变量:模块导入时创建,程序结束时销毁
实例变量:对象创建时创建,对象销毁时销毁
类变量:类定义时创建,程序结束时销毁
02.常量
a.常量的定义
Python 中没有真正的常量概念,通常通过约定来表示常量。
常量是指程序运行过程中不应该被修改的变量。
-----------------------------------------------------------------------------------------------------
常量命名约定:
PI = 3.1415926 # 数学常数
GRAVITY = 9.8 # 重力加速度
MAX_CONNECTIONS = 100 # 最大连接数
DEFAULT_TIMEOUT = 30 # 默认超时时间
API_KEY = "abc123" # API 密钥
-----------------------------------------------------------------------------------------------------
配置文件常量:
# config.py
DATABASE_URL = "mysql://localhost:3306/mydb"
DEBUG_MODE = True
SECRET_KEY = "your-secret-key"
-----------------------------------------------------------------------------------------------------
模块级常量:
# constants.py
WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
WEEKEND = ['Saturday', 'Sunday']
-----------------------------------------------------------------------------------------------------
枚举类常量(Python 3.4+):
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Status(Enum):
PENDING = "pending"
APPROVED = "approved"
REJECTED = "rejected"
-----------------------------------------------------------------------------------------------------
使用枚举:
color = Color.RED
if color == Color.RED:
print("红色")
# 获取枚举值
print(Color.RED.value) # 1
print(Color.RED.name) # "RED"
b.常量命名约定
1.使用全大写字母和下划线(UPPER_CASE)
2.名称应该具有描述性,清楚表达常量的用途
3.避免使用单字母常量(除了数学常数)
4.常量通常定义在模块级别或类的顶部
-----------------------------------------------------------------------------------------------------
好的命名示例:
MAX_PAGE_SIZE = 100
MIN_PASSWORD_LENGTH = 8
DEFAULT_LANGUAGE = "en"
TAX_RATE = 0.08
API_BASE_URL = "https://api.example.com"
-----------------------------------------------------------------------------------------------------
不好的命名示例:
X = 10 # 不清楚含义
MAX = 100 # 太通用
rate = 0.08 # 应该更具体
-----------------------------------------------------------------------------------------------------
常量组织:
# 常量可以按功能分组
# database.py
DB_HOST = "localhost"
DB_PORT = 3306
DB_NAME = "myapp"
DB_USER = "admin"
DB_PASSWORD = "secret"
# api.py
API_VERSION = "v1"
API_TIMEOUT = 30
API_RETRY_COUNT = 3
# 文件常量
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif']
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
c.示例
# 配置常量示例
class Config:
# 数据库配置
DATABASE_CONFIG = {
'host': 'localhost',
'port': 5432,
'database': 'myapp',
'user': 'admin',
'password': 'secret'
}
# API 配置
API_CONFIG = {
'base_url': 'https://api.example.com',
'version': 'v1',
'timeout': 30,
'retry_count': 3
}
# 应用配置
APP_NAME = 'My Application'
VERSION = '1.0.0'
DEBUG = False
LOG_LEVEL = 'INFO'
# 数学常量示例
import math
class MathConstants:
PI = math.pi
E = math.e
GOLDEN_RATIO = (1 + math.sqrt(5)) / 2
# 转换常量
DEGREES_TO_RADIANS = math.pi / 180
RADIANS_TO_DEGREES = 180 / math.pi
# 物理常量示例
class PhysicsConstants:
SPEED_OF_LIGHT = 299792458 # m/s
GRAVITATIONAL_CONSTANT = 6.67430e-11 # m³ kg⁻¹ s⁻²
PLANCK_CONSTANT = 6.62607015e-34 # J⋅s
# 业务常量示例
class BusinessRules:
# 用户等级
USER_LEVELS = {
'BRONZE': 1,
'SILVER': 2,
'GOLD': 3,
'PLATINUM': 4
}
# 折扣率
DISCOUNT_RATES = {
'BRONZE': 0.05,
'SILVER': 0.10,
'GOLD': 0.15,
'PLATINUM': 0.20
}
# 订单状态
ORDER_STATUS = {
'PENDING': 'pending',
'CONFIRMED': 'confirmed',
'SHIPPED': 'shipped',
'DELIVERED': 'delivered',
'CANCELLED': 'cancelled'
}
# 使用常量的示例
def calculate_shipping_cost(weight, distance):
"""计算运费"""
BASE_RATE = 5.0 # 基础费率
RATE_PER_KG = 2.5 # 每公斤费率
RATE_PER_KM = 0.1 # 每公里费率
return BASE_RATE + (weight * RATE_PER_KG) + (distance * RATE_PER_KM)
def get_user_discount(user_level):
"""获取用户折扣"""
DISCOUNT_RATES = {
'BRONZE': 0.05,
'SILVER': 0.10,
'GOLD': 0.15,
'PLATINUM': 0.20
}
return DISCOUNT_RATES.get(user_level, 0.0)
03.代码示例
# 变量基础操作示例
def variable_basics_demo():
# 变量定义和类型
name = "Alice"
age = 25
height = 1.75
is_student = True
scores = [90, 85, 95]
# 查看变量信息
print(f"变量信息:")
print(f" name: {name}, 类型: {type(name)}")
print(f" age: {age}, 类型: {type(age)}")
print(f" height: {height}, 类型: {type(height)}")
print(f" is_student: {is_student}, 类型: {type(is_student)}")
print(f" scores: {scores}, 类型: {type(scores)}")
# 变量重新赋值
age = age + 1
print(f"年龄加1后: {age}")
# 类型检查
print(f"age 是整数吗: {isinstance(age, int)}")
print(f"name 是字符串吗: {isinstance(name, str)}")
# 多重赋值示例
def multiple_assignment_demo():
# 基本多重赋值
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")
# 交换变量
x, y = 10, 20
print(f"交换前: x={x}, y={y}")
x, y = y, x
print(f"交换后: x={x}, y={y}")
# 元组解包
point = (3, 4, 5)
x_coord, y_coord, z_coord = point
print(f"坐标: ({x_coord}, {y_coord}, {z_coord})")
# 列表解包
numbers = [1, 2, 3, 4, 5]
first, second, *rest = numbers
print(f"第一个: {first}, 第二个: {second}, 剩余: {rest}")
first, *middle, last = numbers
print(f"第一个: {first}, 中间: {middle}, 最后: {last}")
# 作用域示例
def scope_demo():
global_var = "全局变量"
def outer_function():
enclosing_var = "嵌套变量"
def inner_function():
local_var = "局部变量"
print(f"内部函数访问: {local_var}")
print(f"内部函数访问: {enclosing_var}")
print(f"内部函数访问: {global_var}")
inner_function()
print(f"外部函数访问: {enclosing_var}")
print(f"外部函数访问: {global_var}")
outer_function()
print(f"全局访问: {global_var}")
# 作用域修改示例
def scope_modification_demo():
# 全局变量修改
counter = 0
def increment():
global counter
counter += 1
print(f"递增后计数: {counter}")
increment()
increment()
print(f"最终计数: {counter}")
# 嵌套作用域修改
def outer():
value = 10
def inner():
nonlocal value
value += 5
print(f"内部修改后: {value}")
inner()
print(f"外部访问: {value}")
outer()
# 常量定义示例
def constants_demo():
# 数学常量
import math
PI = math.pi
E = math.e
# 应用配置常量
APP_NAME = "Python Demo"
VERSION = "1.0.0"
MAX_RETRY_COUNT = 3
DEFAULT_TIMEOUT = 30
# 使用常量
circle_area = PI * 5 ** 2
print(f"半径为5的圆面积: {circle_area:.2f}")
print(f"应用名称: {APP_NAME}")
print(f"版本: {VERSION}")
print(f"最大重试次数: {MAX_RETRY_COUNT}")
# 枚举示例
def enum_demo():
from enum import Enum
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
class Status(Enum):
PENDING = "待处理"
PROCESSING = "处理中"
COMPLETED = "已完成"
FAILED = "失败"
# 使用枚举
today = Weekday.WEDNESDAY
order_status = Status.COMPLETED
print(f"今天是: {today.name} (第{today.value}天)")
print(f"订单状态: {order_status.value}")
# 遍历枚举
print("所有工作日:")
for day in Weekday:
if day.value <= 5:
print(f" {day.name}")
# 配置类常量示例
class AppConfig:
# 数据库配置
DATABASE = {
'host': 'localhost',
'port': 5432,
'name': 'testdb',
'user': 'admin',
'password': 'secret'
}
# API 配置
API = {
'base_url': 'https://api.example.com',
'version': 'v1',
'timeout': 30,
'headers': {
'Content-Type': 'application/json',
'User-Agent': 'PythonApp/1.0'
}
}
# 业务规则
BUSINESS = {
'max_order_amount': 10000,
'min_order_amount': 1,
'tax_rate': 0.08,
'shipping_fee': 5.0
}
def config_demo():
config = AppConfig()
# 访问配置
db_config = config.DATABASE
print(f"数据库配置: {db_config['host']}:{db_config['port']}")
api_config = config.API
print(f"API地址: {api_config['base_url']}/{api_config['version']}")
business_config = config.BUSINESS
print(f"税率: {business_config['tax_rate'] * 100}%")
# 综合示例:计算器应用
class CalculatorConfig:
"""计算器应用配置常量"""
APP_NAME = "Python Calculator"
VERSION = "2.0.0"
MAX_DIGITS = 15
DEFAULT_PRECISION = 2
# 数学常量
MATH_CONSTANTS = {
'PI': 3.14159265359,
'E': 2.71828182846,
'SQRT_2': 1.41421356237
}
# 支持的运算
SUPPORTED_OPERATIONS = {
'+': 'addition',
'-': 'subtraction',
'*': 'multiplication',
'/': 'division',
'^': 'power',
'%': 'modulo'
}
def calculator_demo():
config = CalculatorConfig()
def calculate(a, b, operation):
"""执行计算"""
if operation not in config.SUPPORTED_OPERATIONS:
return "不支持的运算"
try:
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b if b != 0 else "除数不能为零"
elif operation == '^':
return a ** b
elif operation == '%':
return a % b if b != 0 else "除数不能为零"
except Exception as e:
return f"计算错误: {str(e)}"
# 使用配置
print(f"{config.APP_NAME} v{config.VERSION}")
print(f"支持的操作: {list(config.SUPPORTED_OPERATIONS.keys())}")
# 示例计算
result1 = calculate(10, 5, '+')
result2 = calculate(3, 4, '^')
result3 = calculate(20, 0, '/')
print(f"10 + 5 = {result1}")
print(f"3 ^ 4 = {result2}")
print(f"20 / 0 = {result3}")
# 使用数学常量
pi = config.MATH_CONSTANTS['PI']
radius = 5
circle_area = pi * radius ** 2
print(f"半径为{radius}的圆面积: {circle_area:.2f}")
if __name__ == "__main__":
print("=== 变量基础操作 ===")
variable_basics_demo()
print("\n=== 多重赋值 ===")
multiple_assignment_demo()
print("\n=== 作用域演示 ===")
scope_demo()
print("\n=== 作用域修改 ===")
scope_modification_demo()
print("\n=== 常量演示 ===")
constants_demo()
print("\n=== 枚举演示 ===")
enum_demo()
print("\n=== 配置演示 ===")
config_demo()
print("\n=== 计算器应用 ===")
calculator_demo()
1.4 运算符
01.介绍
a.算术运算符
基本算术运算符用于执行基本的数学运算。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| + | 加法 | 两个数相加 | 5 + 3 | 8 |
| - | 减法 | 两个数相减 | 5 - 3 | 2 |
| * | 乘法 | 两个数相乘 | 5 * 3 | 15 |
| / | 除法 | 浮点数除法 | 5 / 2 | 2.5 |
| // | 整除 | 整数除法(向下取整) | 5 // 2 | 2 |
| % | 取模 | 余数 | 5 % 2 | 1 |
| ** | 幂运算 | 指数运算 | 2 ** 3 | 8 |
| - | 负号 | 一元负号 | -5 | -5 |
| + | 正号 | 一元正号 | +5 | 5 |
-----------------------------------------------------------------------------------------------------
详细说明:
# 加法运算
10 + 5 = 15 # 整数加法
3.14 + 2.86 = 6.0 # 浮点数加法
"hello" + "world" = "helloworld" # 字符串连接
[1, 2] + [3, 4] = [1, 2, 3, 4] # 列表连接
-----------------------------------------------------------------------------------------------------
# 减法运算
10 - 5 = 5 # 整数减法
3.14 - 2.86 = 0.28 # 浮点数减法
# 字符串不支持减法
-----------------------------------------------------------------------------------------------------
# 乘法运算
10 * 5 = 50 # 整数乘法
3.14 * 2 = 6.28 # 浮点数乘法
"hi" * 3 = "hihihi" # 字符串重复
[1, 2] * 3 = [1, 2, 1, 2, 1, 2] # 列表重复
-----------------------------------------------------------------------------------------------------
# 除法运算
10 / 3 = 3.333... # 浮点数除法,总是返回浮点数
10 // 3 = 3 # 整数除法,向下取整
10 % 3 = 1 # 取模运算,返回余数
10 ** 3 = 1000 # 幂运算
-----------------------------------------------------------------------------------------------------
# 特殊情况
10 / 0 # ZeroDivisionError: division by zero
10 // 0 # ZeroDivisionError: integer division or modulo by zero
10 % 0 # ZeroDivisionError: integer division or modulo by zero
-----------------------------------------------------------------------------------------------------
# 浮点数精度问题
0.1 + 0.2 = 0.30000000000000004 # 浮点数精度误差
round(0.1 + 0.2, 2) = 0.3 # 使用 round() 解决
b.比较运算符
比较运算符用于比较两个值的大小或是否相等。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| == | 等于 | 检查两个值是否相等 | 5 == 5 | True |
| != | 不等于 | 检查两个值是否不相等 | 5 != 3 | True |
| > | 大于 | 检查左值是否大于右值 | 5 > 3 | True |
| < | 小于 | 检查左值是否小于右值 | 5 < 3 | False |
| >= | 大于等于 | 检查左值是否大于等于右值 | 5 >= 5 | True |
| <= | 小于等于 | 检查左值是否小于等于右值 | 3 <= 5 | True |
-----------------------------------------------------------------------------------------------------
详细说明:
# 数值比较
5 == 5 = True
5 != 3 = True
5 > 3 = True
5 < 3 = False
5 >= 5 = True
3 <= 5 = True
-----------------------------------------------------------------------------------------------------
# 字符串比较(按字典序)
"apple" > "banana" = False # 'a' < 'b'
"hello" == "hello" = True
"abc" < "abd" = True # 比较到不同字符时停止
-----------------------------------------------------------------------------------------------------
# 列表比较(按字典序)
[1, 2, 3] > [1, 2, 2] = True # 比较到不同元素时停止
[1, 2] == [1, 2, 3] = False # 长度不同
-----------------------------------------------------------------------------------------------------
# 布尔值比较
True == 1 = True # True 转换为 1
False == 0 = True # False 转换为 0
True > False = True # 1 > 0
-----------------------------------------------------------------------------------------------------
# None 比较
None == None = True
None != None = False
# None 不能与数值比较,会报 TypeError
-----------------------------------------------------------------------------------------------------
# 类型比较
isinstance(5, int) = True # 检查类型
type(5) == int = True # 另一种类型检查方式
c.逻辑运算符
逻辑运算符用于执行布尔逻辑运算。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| and | 逻辑与 | 两个条件都为真时为真 | True and True | True |
| or | 逻辑或 | 两个条件中有一个为真时为真 | True or False | True |
| not | 逻辑非 | 取反 | not True | False |
-----------------------------------------------------------------------------------------------------
详细说明:
# and 运算符(短路求值)
True and True = True
True and False = False
False and True = False
False and False = False
-----------------------------------------------------------------------------------------------------
# and 短路特性:如果第一个表达式为 False,不会计算第二个表达式
def side_effect():
print("执行了副作用函数")
return True
False and side_effect() # 不会打印 "执行了副作用函数"
-----------------------------------------------------------------------------------------------------
# or 运算符(短路求值)
True or True = True
True or False = True
False or True = True
False or False = False
-----------------------------------------------------------------------------------------------------
# or 短路特性:如果第一个表达式为 True,不会计算第二个表达式
True or side_effect() # 不会打印 "执行了副作用函数"
-----------------------------------------------------------------------------------------------------
# not 运算符
not True = False
not False = True
not 0 = True # 0 转换为 False
not 1 = False # 1 转换为 True
not "" = True # 空字符串转换为 False
not "hello" = False # 非空字符串转换为 True
-----------------------------------------------------------------------------------------------------
# 复杂逻辑表达式
age = 25
has_license = True
can_drive = (age >= 18) and has_license # True
-----------------------------------------------------------------------------------------------------
# 运算符优先级:not > and > or
True or False and False # 相当于 True or (False and False) = True
(True or False) and False # 相当于 True and False = False
d.位运算符
位运算符对整数的二进制位进行操作。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| & | 按位与 | 两个数对应位都为1时为1 | 5 & 3 | 1 |
| \| | 按位或 | 两个数对应位有一个为1时为1 | 5 \| 3 | 7 |
| ^ | 按位异或 | 两个数对应位不同时为1 | 5 ^ 3 | 6 |
| ~ | 按位取反 | 对所有位取反 | ~5 | -6 |
| << | 左移 | 所有位左移指定位数 | 5 << 2 | 20 |
| >> | 右移 | 所有位右移指定位数 | 5 >> 1 | 2 |
-----------------------------------------------------------------------------------------------------
详细说明:
# 按位与 (&)
# 5 = 0b0101, 3 = 0b0011
5 & 3 = 0b0001 = 1
-----------------------------------------------------------------------------------------------------
# 按位或 (|)
# 5 = 0b0101, 3 = 0b0011
5 | 3 = 0b0111 = 7
-----------------------------------------------------------------------------------------------------
# 按位异或 (^)
# 5 = 0b0101, 3 = 0b0011
5 ^ 3 = 0b0110 = 6
-----------------------------------------------------------------------------------------------------
# 按位取反 (~)
# ~x = -(x + 1)
~5 = -6
~(-3) = 2
-----------------------------------------------------------------------------------------------------
# 左移 (<<)
# x << n = x * (2 ** n)
5 << 2 = 5 * 4 = 20 # 0b0101 << 2 = 0b10100
-----------------------------------------------------------------------------------------------------
# 右移 (>>)
# x >> n = x // (2 ** n)(整数除法)
5 >> 1 = 2 # 0b0101 >> 1 = 0b0010
-----------------------------------------------------------------------------------------------------
# 实际应用
# 检查特定位是否为1
def check_bit(number, position):
mask = 1 << position
return (number & mask) != 0
# 设置特定位为1
def set_bit(number, position):
mask = 1 << position
return number | mask
# 清除特定位
def clear_bit(number, position):
mask = ~(1 << position)
return number & mask
# 权限管理示例
READ = 1 # 0b0001
WRITE = 2 # 0b0010
EXECUTE = 4 # 0b0100
user_permissions = READ | WRITE # 0b0011
has_read = (user_permissions & READ) != 0 # True
has_execute = (user_permissions & EXECUTE) != 0 # False
e.赋值运算符
赋值运算符用于为变量赋值,包括简单赋值和复合赋值。
| 运算符 | 名称 | 描述 | 示例 | 等价于 |
|--------|------|------|------|--------|
| = | 赋值 | 将右值赋给左值 | x = 5 | - |
| += | 加法赋值 | 加并赋值 | x += 3 | x = x + 3 |
| -= | 减法赋值 | 减并赋值 | x -= 3 | x = x - 3 |
| *= | 乘法赋值 | 乘并赋值 | x *= 3 | x = x * 3 |
| /= | 除法赋值 | 除并赋值 | x /= 3 | x = x / 3 |
| //= | 整除赋值 | 整除并赋值 | x //= 3 | x = x // 3 |
| %= | 取模赋值 | 取模并赋值 | x %= 3 | x = x % 3 |
| **= | 幂赋值 | 幂并赋值 | x **= 3 | x = x ** 3 |
| <<= | 左移赋值 | 左移并赋值 | x <<= 2 | x = x << 2 |
| >>= | 右移赋值 | 右移并赋值 | x >>= 2 | x = x >> 2 |
| &= | 按位与赋值 | 按位与并赋值 | x &= 3 | x = x & 3 |
| \|= | 按位或赋值 | 按位或并赋值 | x \|= 3 | x = x \| 3 |
| ^= | 按位异或赋值 | 按位异或并赋值 | x ^= 3 | x = x ^ 3 |
-----------------------------------------------------------------------------------------------------
详细说明:
# 基本赋值
x = 10
y = x + 5 # y = 15
-----------------------------------------------------------------------------------------------------
# 复合赋值
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 7 # x = 3
x %= 2 # x = 1
x **= 3 # x = 1
-----------------------------------------------------------------------------------------------------
# 字符串复合赋值
s = "hello"
s += " world" # s = "hello world"
s *= 2 # s = "hello worldhello world"
-----------------------------------------------------------------------------------------------------
# 列表复合赋值(extend)
lst = [1, 2]
lst += [3, 4] # lst = [1, 2, 3, 4]
-----------------------------------------------------------------------------------------------------
# 多重赋值
a = b = c = 0 # a、b、c 都赋值为 0
-----------------------------------------------------------------------------------------------------
# 链式赋值
x = y = z = 5
-----------------------------------------------------------------------------------------------------
# 注意:赋值运算符的优先级很低
a = 5 + 3 * 2 # 先计算 3 * 2,再加 5,最后赋值
f.成员运算符
成员运算符用于测试序列中是否存在指定的值。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| in | 成员资格 | 检查值是否在序列中 | 3 in [1,2,3] | True |
| not in | 非成员资格 | 检查值是否不在序列中 | 4 not in [1,2,3] | True |
-----------------------------------------------------------------------------------------------------
详细说明:
# 列表成员检查
numbers = [1, 2, 3, 4, 5]
3 in numbers = True
6 in numbers = False
6 not in numbers = True
-----------------------------------------------------------------------------------------------------
# 字符串成员检查
text = "hello world"
"hello" in text = True
"world" in text = True
"python" in text = False
-----------------------------------------------------------------------------------------------------
# 元组成员检查
point = (1, 2, 3)
2 in point = True
4 in point = False
-----------------------------------------------------------------------------------------------------
# 字典成员检查(检查键)
person = {"name": "Alice", "age": 25}
"name" in person = True # 检查键
"Alice" in person = False # 不检查值
"Alice" in person.values() = True # 检查值
-----------------------------------------------------------------------------------------------------
# 集合成员检查
colors = {"red", "green", "blue"}
"red" in colors = True
"yellow" in colors = False
-----------------------------------------------------------------------------------------------------
# 范围成员检查
numbers = range(10) # 0-9
5 in numbers = True
10 in numbers = False
-----------------------------------------------------------------------------------------------------
# 字符串的子串检查
"ell" in "hello" = True
"xyz" not in "hello" = True
-----------------------------------------------------------------------------------------------------
# 性能考虑:
# 列表:O(n) 时间复杂度,线性搜索
# 集合/字典:O(1) 平均时间复杂度,哈希查找
-----------------------------------------------------------------------------------------------------
# 大量数据时的性能优化
large_list = list(range(1000000))
999999 in large_list # 比较慢,O(n)
-----------------------------------------------------------------------------------------------------
large_set = set(range(1000000))
999999 in large_set # 很快,O(1)
g.身份运算符
身份运算符用于比较两个对象的内存地址。
| 运算符 | 名称 | 描述 | 示例 | 结果 |
|--------|------|------|------|------|
| is | 身份相同 | 检查两个对象是否指向同一个对象 | a is b | 取决于内存地址 |
| is not | 身份不同 | 检查两个对象是否指向不同对象 | a is not b | 取决于内存地址 |
-----------------------------------------------------------------------------------------------------
详细说明:
# 对象身份 vs 值相等
a = [1, 2, 3]
b = [1, 2, 3]
c = a
-----------------------------------------------------------------------------------------------------
a == b = True # 值相等
a is b = False # 身份不同(不同对象)
a is c = True # 身份相同(同一对象)
-----------------------------------------------------------------------------------------------------
# 小整数缓存(Python 优化)
x = 5
y = 5
x is y = True # 小整数(-5 到 256)被缓存
-----------------------------------------------------------------------------------------------------
x = 1000
y = 1000
x is y = False # 大整数可能不是同一对象(取决于实现)
-----------------------------------------------------------------------------------------------------
# 字符串缓存
s1 = "hello"
s2 = "hello"
s1 is s2 = True # 短字符串可能被缓存
-----------------------------------------------------------------------------------------------------
s1 = "hello world python"
s2 = "hello world python"
s1 is s2 = False # 长字符串可能不是同一对象
-----------------------------------------------------------------------------------------------------
# None 是单例
a = None
b = None
a is b = True # None 是单例对象
-----------------------------------------------------------------------------------------------------
# 布尔值是单例
a = True
b = True
a is b = True # True 是单例
-----------------------------------------------------------------------------------------------------
# 检查对象身份的用途
def check_none(value):
if value is None: # 推荐:检查 None
print("值为 None")
if value == None: # 不推荐:可能调用 __eq__ 方法
print("值为 None")
-----------------------------------------------------------------------------------------------------
# 查看内存地址
a = [1, 2, 3]
b = [1, 2, 3]
id(a) # 返回 a 的内存地址
id(b) # 返回 b 的内存地址
a is b # 比较内存地址
02.代码示例
# 算术运算符示例
def arithmetic_operators_demo():
print("=== 算术运算符 ===")
# 基本运算
a, b = 10, 3
print(f"a = {a}, b = {b}")
print(f"a + b = {a + b}") # 13
print(f"a - b = {a - b}") # 7
print(f"a * b = {a * b}") # 30
print(f"a / b = {a / b}") # 3.333...
print(f"a // b = {a // b}") # 3
print(f"a % b = {a % b}") # 1
print(f"a ** b = {a ** b}") # 1000
# 字符串运算
s1, s2 = "hello", "world"
print(f"'{s1}' + '{s2}' = '{s1 + s2}'") # helloworld
print(f"'{s1}' * 3 = '{s1 * 3}'") # hellohellohello
# 列表运算
lst1, lst2 = [1, 2], [3, 4]
print(f"{lst1} + {lst2} = {lst1 + lst2}") # [1, 2, 3, 4]
print(f"{lst1} * 2 = {lst1 * 2}") # [1, 2, 1, 2]
# 比较运算符示例
def comparison_operators_demo():
print("\n=== 比较运算符 ===")
a, b = 5, 3
print(f"a = {a}, b = {b}")
print(f"a == b = {a == b}") # False
print(f"a != b = {a != b}") # True
print(f"a > b = {a > b}") # True
print(f"a < b = {a < b}") # False
print(f"a >= b = {a >= b}") # True
print(f"a <= b = {a <= b}") # True
# 字符串比较
s1, s2 = "apple", "banana"
print(f"'{s1}' > '{s2}' = {s1 > s2}") # False
print(f"'{s1}' == '{s1}' = {s1 == s1}") # True
# 列表比较
lst1, lst2 = [1, 2, 3], [1, 2, 4]
print(f"{lst1} < {lst2} = {lst1 < lst2}") # True
# 逻辑运算符示例
def logical_operators_demo():
print("\n=== 逻辑运算符 ===")
# 基本逻辑运算
print(f"True and True = {True and True}")
print(f"True and False = {True and False}")
print(f"True or False = {True or False}")
print(f"False or False = {False or False}")
print(f"not True = {not True}")
print(f"not False = {not False}")
# 短路求值示例
def expensive_operation():
print("执行昂贵操作")
return True
print("短路求值测试:")
False and expensive_operation() # 不会打印
print("第一部分完成")
True or expensive_operation() # 不会打印
print("第二部分完成")
# 实际应用场景
age = 20
has_license = True
has_insurance = False
# 检查是否可以开车
can_drive = (age >= 18) and has_license
print(f"年龄{age}岁,有驾照:{has_license},可以开车:{can_drive}")
# 检查是否满足任一条件
has_discount = age < 18 or age > 65
print(f"年龄{age}岁,有折扣:{has_discount}")
# 位运算符示例
def bitwise_operators_demo():
print("\n=== 位运算符 ===")
a, b = 5, 3
print(f"a = {a} (二进制: {bin(a)})")
print(f"b = {b} (二进制: {bin(b)})")
print(f"a & b = {a & b} (二进制: {bin(a & b)})") # 1
print(f"a | b = {a | b} (二进制: {bin(a | b)})") # 7
print(f"a ^ b = {a ^ b} (二进制: {bin(a ^ b)})") # 6
print(f"~a = {~a}") # -6
print(f"a << 2 = {a << 2} (二进制: {bin(a << 2)})") # 20
print(f"a >> 1 = {a >> 1} (二进制: {bin(a >> 1)})") # 2
# 权限管理示例
READ = 1 # 0b0001
WRITE = 2 # 0b0010
EXECUTE = 4 # 0b0100
# 设置用户权限
user_permissions = READ | WRITE # 0b0011
print(f"用户权限: {user_permissions} (二进制: {bin(user_permissions)})")
# 检查权限
has_read = (user_permissions & READ) != 0
has_write = (user_permissions & WRITE) != 0
has_execute = (user_permissions & EXECUTE) != 0
print(f"读权限: {has_read}")
print(f"写权限: {has_write}")
print(f"执行权限: {has_execute}")
# 添加权限
user_permissions |= EXECUTE # 添加执行权限
print(f"添加执行权限后: {user_permissions} (二进制: {bin(user_permissions)})")
# 赋值运算符示例
def assignment_operators_demo():
print("\n=== 赋值运算符 ===")
x = 10
print(f"初始值: x = {x}")
x += 3
print(f"x += 3: x = {x}") # 13
x -= 5
print(f"x -= 5: x = {x}") # 8
x *= 2
print(f"x *= 2: x = {x}") # 16
x //= 3
print(f"x //= 3: x = {x}") # 5
x %= 3
print(f"x %= 3: x = {x}") # 2
x **= 3
print(f"x **= 3: x = {x}") # 8
# 字符串操作
s = "hello"
s += " world"
print(f"s += ' world': '{s}'") # hello world
s *= 2
print(f"s *= 2: '{s}'") # hello worldhello world
# 成员运算符示例
def membership_operators_demo():
print("\n=== 成员运算符 ===")
# 列表成员检查
numbers = [1, 2, 3, 4, 5]
print(f"列表: {numbers}")
print(f"3 in numbers: {3 in numbers}")
print(f"6 in numbers: {6 in numbers}")
print(f"6 not in numbers: {6 not in numbers}")
# 字符串成员检查
text = "hello world"
print(f"文本: '{text}'")
print(f"'hello' in text: {'hello' in text}")
print(f"'python' in text: {'python' in text}")
# 字典成员检查
person = {"name": "Alice", "age": 25}
print(f"字典: {person}")
print(f"'name' in person: {'name' in person}")
print(f"'Alice' in person: {'Alice' in person}")
print(f"'Alice' in person.values(): {'Alice' in person.values()}")
# 集合成员检查
colors = {"red", "green", "blue"}
print(f"集合: {colors}")
print(f"'red' in colors: {'red' in colors}")
print(f"'yellow' in colors: {'yellow' in colors}")
# 性能比较
import time
large_list = list(range(100000))
large_set = set(range(100000))
# 列表查找
start = time.time()
99999 in large_list
list_time = time.time() - start
# 集合查找
start = time.time()
99999 in large_set
set_time = time.time() - start
print(f"列表查找时间: {list_time:.6f}秒")
print(f"集合查找时间: {set_time:.6f}秒")
print(f"集合查找比列表快 {list_time/set_time:.0f} 倍")
# 身份运算符示例
def identity_operators_demo():
print("\n=== 身份运算符 ===")
# 对象身份 vs 值相等
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(f"a = {a}")
print(f"b = {b}")
print(f"c = a = {c}")
print(f"a == b: {a == b}") # True (值相等)
print(f"a is b: {a is b}") # False (身份不同)
print(f"a is c: {a is c}") # True (身份相同)
print(f"a 的内存地址: {id(a)}")
print(f"b 的内存地址: {id(b)}")
print(f"c 的内存地址: {id(c)}")
# 小整数缓存
x = 100
y = 100
print(f"x = {x}, y = {y}")
print(f"x is y: {x is y}") # True (小整数缓存)
x = 1000
y = 1000
print(f"x = {x}, y = {y}")
print(f"x is y: {x is y}") # False (可能不是同一对象)
# None 是单例
a = None
b = None
print(f"a = None, b = None")
print(f"a is b: {a is b}") # True
# 正确的 None 检查方式
def process_value(value):
if value is None: # 推荐
return "值为 None"
elif value == None: # 不推荐
return "值等于 None"
else:
return "值不为 None"
print(f"process_value(None): {process_value(None)}")
print(f"process_value(0): {process_value(0)}")
# 运算符优先级示例
def operator_precedence_demo():
print("\n=== 运算符优先级 ===")
# 运算符优先级(从高到低):
# 1. 括号 ()
# 2. 幂运算 **
# 3. 正负号 +x, -x
# 4. 乘除取模 *, /, //, %
# 5. 加减 +, -
# 6. 位移 <<, >>
# 7. 位与 &
# 8. 位异或 ^
# 9. 位或 |
# 10. 比较 ==, !=, >, <, >=, <=
# 11. 身份 is, is not
# 12. 成员 in, not in
# 13. 逻辑非 not
# 14. 逻辑与 and
# 15. 逻辑或 or
# 16. 赋值 =, +=, -=, 等
print("运算符优先级示例:")
result = 2 + 3 * 4
print(f"2 + 3 * 4 = {result}") # 14 (先乘后加)
result = (2 + 3) * 4
print(f"(2 + 3) * 4 = {result}") # 20 (括号优先)
result = 2 ** 3 ** 2
print(f"2 ** 3 ** 2 = {result}") # 512 (右结合)
result = (2 ** 3) ** 2
print(f"(2 ** 3) ** 2 = {result}") # 64
# 逻辑运算符优先级
result = True or False and False
print(f"True or False and False = {result}") # True (and 优先于 or)
result = (True or False) and False
print(f"(True or False) and False = {result}") # False
result = not True or False
print(f"not True or False = {result}") # False (not 优先于 or)
# 成员和身份运算符
lst = [1, 2, 3]
result = 2 in lst and len(lst) > 2
print(f"2 in lst and len(lst) > 2 = {result}") # True
# 综合运算符示例
def comprehensive_demo():
print("\n=== 综合应用示例 ===")
# 计算圆的面积和周长
import math
radius = 5
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print(f"半径为 {radius} 的圆:")
print(f"面积: {area:.2f}")
print(f"周长: {circumference:.2f}")
# 温度转换
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")
# 判断闰年
year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year} 年是闰年: {is_leap}")
# 学生成绩等级
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(f"分数 {score} 对应等级: {grade}")
# 位运算应用:颜色RGB值处理
r, g, b = 255, 128, 64
rgb = (r << 16) | (g << 8) | b
print(f"RGB({r}, {g}, {b}) -> 整数: {rgb}")
# 从整数中提取RGB
r2 = (rgb >> 16) & 0xFF
g2 = (rgb >> 8) & 0xFF
b2 = rgb & 0xFF
print(f"整数 {rgb} -> RGB({r2}, {g2}, {b2})")
if __name__ == "__main__":
arithmetic_operators_demo()
comparison_operators_demo()
logical_operators_demo()
bitwise_operators_demo()
assignment_operators_demo()
membership_operators_demo()
identity_operators_demo()
operator_precedence_demo()
comprehensive_demo()
1.5 流程控制
01.介绍
a.条件语句
根据条件表达式的真假来决定执行哪个代码块。
基本结构:if, if-else, if-elif-else
支持:布尔表达式、比较表达式、逻辑表达式
b.循环语句
重复执行代码块,直到满足特定条件。
主要类型:for 循环、while 循环
支持:嵌套循环、循环控制
c.控制语句
在循环中改变执行流程的语句。
主要语句:break、continue、pass
02.条件语句
a.if 语句
基本语法:
if condition:
# 条件为真时执行的代码块
statement1
statement2
-----------------------------------------------------------------------------------------------------
示例:
age = 18
if age >= 18:
print("您已成年")
print("可以投票")
-----------------------------------------------------------------------------------------------------
# 复杂条件
username = "admin"
password = "123456"
if username == "admin" and password == "123456":
print("登录成功")
-----------------------------------------------------------------------------------------------------
# 多行条件
score = 85
if (score >= 80 and
score <= 100 and
not is_blacklisted(student_id)):
print("成绩优秀")
b.if-else 语句
基本语法:
if condition:
# 条件为真时执行
true_statements
else:
# 条件为假时执行
false_statements
-----------------------------------------------------------------------------------------------------
示例:
age = 16
if age >= 18:
print("您已成年")
else:
print("您未成年")
-----------------------------------------------------------------------------------------------------
# 嵌套 if-else
number = 0
if number > 0:
print("正数")
else:
if number < 0:
print("负数")
else:
print("零")
c.if-elif-else 语句
基本语法:
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
default_statements
-----------------------------------------------------------------------------------------------------
示例:
score = 75
if score >= 90:
grade = 'A'
print("优秀")
elif score >= 80:
grade = 'B'
print("良好")
elif score >= 70:
grade = 'C'
print("中等")
elif score >= 60:
grade = 'D'
print("及格")
else:
grade = 'F'
print("不及格")
print(f"成绩等级: {grade}")
-----------------------------------------------------------------------------------------------------
# 多条件判断
weather = "rainy"
temperature = 15
if weather == "sunny" and temperature > 20:
activity = "去海滩"
elif weather == "rainy":
activity = "看电影"
elif weather == "snowy":
activity = "堆雪人"
else:
activity = "待在家里"
print(f"建议活动: {activity}")
d.三元运算符
Python 的条件表达式(三元运算符)提供了一种简洁的条件赋值方式。
-----------------------------------------------------------------------------------------------------
基本语法:
value_if_true if condition else value_if_false
-----------------------------------------------------------------------------------------------------
示例:
age = 20
status = "成年" if age >= 18 else "未成年"
print(status) # "成年"
# 传统 if-else vs 三元运算符
# 传统方式:
if x > y:
max_val = x
else:
max_val = y
# 三元运算符:
max_val = x if x > y else y
# 嵌套三元运算符
score = 75
grade = ('A' if score >= 90 else
'B' if score >= 80 else
'C' if score >= 70 else
'F')
print(grade) # "C"
# 列表推导式中使用
numbers = [1, 2, 3, 4, 5]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # [2, 4]
# 函数参数默认值
def greet(name, formal=False):
title = "Mr./Ms." if formal else ""
return f"Hello, {title}{name}"
03.循环语句
a.for 循环
for 循环用于遍历序列(列表、元组、字符串等)或其他可迭代对象。
-----------------------------------------------------------------------------------------------------
基本语法:
for variable in iterable:
# 循环体
statement1
statement2
# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"水果: {fruit}")
# 遍历字符串
text = "hello"
for char in text:
print(f"字符: {char}")
# 遍历范围
for i in range(5): # 0, 1, 2, 3, 4
print(f"数字: {i}")
# 遍历字典
person = {"name": "Alice", "age": 25, "city": "Beijing"}
# 遍历键
for key in person:
print(f"键: {key}")
# 遍历键值
for key, value in person.items():
print(f"{key}: {value}")
# 遍历值
for value in person.values():
print(f"值: {value}")
# range() 函数用法
# range(stop) - 0 到 stop-1
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop) - start 到 stop-1
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# range(start, stop, step) - 指定步长
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# 倒序
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
# enumerate() 函数 - 同时获取索引和值
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
# 指定起始索引
for index, fruit in enumerate(fruits, 1):
print(f"第 {index} 个水果: {fruit}")
# zip() 函数 - 同时遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["Beijing", "Shanghai", "Guangzhou"]
for name, age, city in zip(names, ages, cities):
print(f"{name}({age}岁) 来自 {city}")
# 列表推导式(在循环中创建列表)
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
b.while 循环
while 循环在条件为真时重复执行代码块。
-----------------------------------------------------------------------------------------------------
基本语法:
while condition:
# 循环体
statement1
statement2
# 基本 while 循环
count = 0
while count < 5:
print(f"计数: {count}")
count += 1
# 计算总和
total = 0
number = 1
while number <= 100:
total += number
number += 1
print(f"1到100的和: {total}")
# 输入验证
while True:
user_input = input("请输入一个正数: ")
try:
number = float(user_input)
if number > 0:
print(f"您输入的数字是: {number}")
break
else:
print("请输入正数!")
except ValueError:
print("请输入有效的数字!")
# 游戏循环示例
import random
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("猜数字游戏!我想了一个1-100的数字。")
while attempts < max_attempts:
try:
guess = int(input(f"第{attempts + 1}次猜测: "))
attempts += 1
if guess == secret_number:
print(f"恭喜!你用{attempts}次猜对了!")
break
elif guess < secret_number:
print("太小了!")
else:
print("太大了!")
if attempts == max_attempts:
print(f"游戏结束!答案是 {secret_number}")
except ValueError:
print("请输入有效的数字!")
# while-else 结构
count = 0
while count < 3:
print(f"循环中: {count}")
count += 1
else:
print("循环正常结束") # 只有在没有 break 时执行
# 带条件的 while 循环
number = 10
while number > 0:
print(number)
number -= 2
# 使用标志变量
running = True
while running:
command = input("输入命令 (quit 退出): ")
if command == "quit":
running = False
elif command == "help":
print("可用命令: help, quit")
else:
print(f"未知命令: {command}")
c.嵌套循环
嵌套循环是指在一个循环内部包含另一个循环。
# 基本嵌套循环
for i in range(3): # 外层循环
for j in range(2): # 内层循环
print(f"i={i}, j={j}")
# 输出乘法表
print("乘法表:")
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}x{i}={i*j}", end=" ")
print() # 换行
# 处理二维列表
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=" ")
print()
# 查找二维列表中的最大值
max_value = matrix[0][0]
max_position = (0, 0)
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if element > max_value:
max_value = element
max_position = (i, j)
print(f"最大值 {max_value} 在位置 {max_position}")
# 图形输出
size = 5
for i in range(size):
for j in range(size):
if i == j or i + j == size - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
# 学生成绩处理
students = [
{"name": "Alice", "scores": [85, 90, 78]},
{"name": "Bob", "scores": [76, 88, 92]},
{"name": "Charlie", "scores": [90, 85, 88]}
]
for student in students:
print(f"\n学生: {student['name']}")
total = 0
for score in student['scores']:
print(f" 成绩: {score}")
total += score
average = total / len(student['scores'])
print(f" 平均分: {average:.1f}")
04.控制语句
a.break 语句
break 语句用于立即终止当前循环,跳出循环体。
-----------------------------------------------------------------------------------------------------
# 在 for 循环中使用 break
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number == 6:
print("找到数字6,停止搜索")
break
print(f"检查: {number}")
# 查找第一个满足条件的元素
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
for fruit in fruits:
if fruit.startswith('o'): # 以 'o' 开头
print(f"找到以'o'开头的水果: {fruit}")
break
# 在 while 循环中使用 break
count = 0
while True:
print(f"计数: {count}")
if count >= 5:
break
count += 1
# 密码输入验证
correct_password = "123456"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input(f"请输入密码 (第{attempts + 1}次): ")
if password == correct_password:
print("密码正确!")
break
attempts += 1
print("密码错误!")
else:
print("密码错误次数过多,账户被锁定!")
b.continue 语句
continue 语句用于跳过当前迭代的剩余代码,继续下一次迭代。
-----------------------------------------------------------------------------------------------------
# 跳过特定元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0: # 偶数
continue
print(f"奇数: {number}")
# 过滤数据
students = [
{"name": "Alice", "score": 85, "active": True},
{"name": "Bob", "score": 92, "active": False},
{"name": "Charlie", "score": 78, "active": True},
{"name": "David", "score": 65, "active": True}
]
for student in students:
if not student['active']:
continue # 跳过非活跃学生
if student['score'] < 80:
continue # 跳过低分学生
print(f"优秀学生: {student['name']} - {student['score']}分")
# 输入验证
while True:
user_input = input("请输入一个数字 (输入 'quit' 退出): ")
if user_input.lower() == 'quit':
break
if not user_input.isdigit():
print("请输入有效数字!")
continue
number = int(user_input)
print(f"您输入的数字是: {number}")
# 处理文件内容(跳过空行和注释)
lines = [
"# 这是一个配置文件",
"",
"host=localhost",
"# 数据库配置",
"port=5432",
"",
"username=admin"
]
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
print(f"配置项: {line}")
c.pass 语句
pass 语句是一个空操作,用于语法上需要语句但不需要任何操作的地方。
-----------------------------------------------------------------------------------------------------
# 最小类定义
class EmptyClass:
pass
# 最小函数定义
def placeholder_function():
pass # TODO: 实现这个函数
# 条件语句中的占位符
age = 15
if age >= 18:
print("您已成年")
else:
pass # 暂时不处理未成年情况
# 异常处理中的占位符
try:
# 一些可能出错的代码
result = 10 / 0
except ZeroDivisionError:
pass # 忽略除零错误
# 循环中的占位符
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
pass # 暂时不处理偶数
else:
print(f"奇数: {number}")
# 开发过程中的占位符
class Game:
def start(self):
pass # TODO: 实现游戏开始逻辑
def pause(self):
pass # TODO: 实现游戏暂停逻辑
def stop(self):
pass # TODO: 实现游戏停止逻辑
# 协议或接口的实现
class Drawable:
def draw(self):
pass # 子类需要实现这个方法
class Circle(Drawable):
def draw(self):
print("画一个圆形")
class Rectangle(Drawable):
def draw(self):
print("画一个矩形")
05.代码示例
# 条件语句综合示例
def conditional_statements_demo():
print("=== 条件语句示例 ===")
# 成绩等级判断
def get_grade(score):
if not isinstance(score, (int, float)):
return "无效成绩"
if score < 0 or score > 100:
return "成绩超出范围"
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
scores = [95, 85, 75, 65, 55, 105, -5, "abc"]
for score in scores:
grade = get_grade(score)
print(f"成绩 {score} -> 等级 {grade}")
# 用户登录验证
def check_login(username, password):
# 模拟数据库
users = {
"admin": {"password": "123456", "role": "administrator"},
"user1": {"password": "abc123", "role": "user"},
"guest": {"password": "guest123", "role": "guest"}
}
if not username or not password:
return "用户名和密码不能为空"
if username not in users:
return "用户不存在"
user_info = users[username]
if password != user_info["password"]:
return "密码错误"
if user_info["role"] == "administrator":
return f"欢迎管理员 {username}!"
elif user_info["role"] == "user":
return f"欢迎用户 {username}!"
else:
return f"欢迎访客 {username}!"
# 测试登录
test_cases = [
("admin", "123456"),
("user1", "wrong"),
("nonexistent", "123"),
("", "password"),
("guest", "guest123")
]
for username, password in test_cases:
result = check_login(username, password)
print(f"登录测试 {username}/{password}: {result}")
# 循环语句综合示例
def loop_statements_demo():
print("\n=== 循环语句示例 ===")
# 数字处理
def analyze_numbers(numbers):
if not numbers:
return "空列表"
positives = []
negatives = []
zeros = []
for num in numbers:
if num > 0:
positives.append(num)
elif num < 0:
negatives.append(num)
else:
zeros.append(num)
return {
"正数": positives,
"负数": negatives,
"零": zeros,
"最大值": max(numbers),
"最小值": min(numbers),
"平均值": sum(numbers) / len(numbers)
}
test_numbers = [5, -3, 0, 8, -2, 0, 7, -1]
result = analyze_numbers(test_numbers)
print(f"数字分析结果:")
for key, value in result.items():
if isinstance(value, list):
print(f" {key}: {value}")
else:
print(f" {key}: {value:.2f}")
# 素数判断
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# 查找指定范围内的素数
def find_primes(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
prime_range = find_primes(1, 100)
print(f"1-100之间的素数: {prime_range}")
# 斐波那契数列
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fib = [0, 1]
while len(fib) < n:
next_num = fib[-1] + fib[-2]
fib.append(next_num)
return fib
fib_sequence = fibonacci(15)
print(f"斐波那契数列前15项: {fib_sequence}")
# 控制语句综合示例
def control_statements_demo():
print("\n=== 控制语句示例 ===")
# 搜索算法示例
def linear_search(arr, target):
"""线性搜索,返回目标元素的索引"""
for index, element in enumerate(arr):
if element == target:
return index
return -1
def binary_search(arr, target):
"""二分搜索,要求有序数组"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# 测试搜索
unsorted_list = [64, 34, 25, 12, 22, 11, 90, 88, 76, 50, 42]
sorted_list = sorted(unsorted_list)
target = 25
linear_result = linear_search(unsorted_list, target)
binary_result = binary_search(sorted_list, target)
print(f"在 {unsorted_list} 中线性搜索 {target}: 索引 {linear_result}")
print(f"在 {sorted_list} 中二分搜索 {target}: 索引 {binary_result}")
# 数据过滤和处理
def process_student_data(students):
processed = []
for student in students:
# 跳过无效数据
if not student.get('name') or student.get('age', 0) <= 0:
continue
# 只处理活跃学生
if not student.get('active', True):
continue
# 计算平均分
scores = student.get('scores', [])
if not scores:
continue
avg_score = sum(scores) / len(scores)
# 添加处理结果
processed.append({
'name': student['name'],
'age': student['age'],
'avg_score': avg_score,
'grade': get_letter_grade(avg_score)
})
return processed
def get_letter_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# 测试学生数据处理
student_data = [
{"name": "Alice", "age": 20, "scores": [85, 90, 78], "active": True},
{"name": "Bob", "age": 21, "scores": [92, 88, 95], "active": True},
{"name": "", "age": 22, "scores": [75, 80, 82], "active": True}, # 无效名字
{"name": "Charlie", "age": 0, "scores": [88, 85, 90], "active": True}, # 无效年龄
{"name": "David", "age": 23, "scores": [], "active": True}, # 无成绩
{"name": "Eve", "age": 19, "scores": [65, 70, 68], "active": False}, # 非活跃
]
processed_students = process_student_data(student_data)
print("处理后的学生数据:")
for student in processed_students:
print(f" {student['name']}: {student['avg_score']:.1f} ({student['grade']})")
# 嵌套循环综合示例
def nested_loops_demo():
print("\n=== 嵌套循环示例 ===")
# 矩阵运算
def matrix_multiply(A, B):
"""矩阵乘法"""
if len(A[0]) != len(B):
raise ValueError("矩阵维度不匹配")
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
element = 0
for k in range(len(B)):
element += A[i][k] * B[k][j]
row.append(element)
result.append(row)
return result
# 测试矩阵乘法
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = matrix_multiply(A, B)
print("矩阵乘法:")
print(f"A = {A}")
print(f"B = {B}")
print(f"A × B = {C}")
# 购物车分析
def analyze_sales_data():
# 模拟销售数据:[产品ID, 销量, 价格]
sales_data = [
[1, 5, 10.99], [2, 3, 24.99], [1, 2, 10.99],
[3, 1, 99.99], [2, 4, 24.99], [3, 2, 99.99],
[1, 1, 10.99], [4, 3, 49.99], [2, 1, 24.99]
]
# 产品信息
products = {
1: "笔记本电脑",
2: "无线鼠标",
3: "机械键盘",
4: "显示器"
}
# 统计每个产品的总销量和总收入
product_stats = {}
for sale in sales_data:
product_id, quantity, price = sale
if product_id not in product_stats:
product_stats[product_id] = {
'name': products[product_id],
'total_quantity': 0,
'total_revenue': 0
}
product_stats[product_id]['total_quantity'] += quantity
product_stats[product_id]['total_revenue'] += quantity * price
# 输出统计结果
print("\n产品销售统计:")
print(f"{'产品':<12} {'销量':<8} {'收入':<12}")
print("-" * 35)
for product_id, stats in product_stats.items():
print(f"{stats['name']:<12} {stats['total_quantity']:<8} "
f"{stats['total_revenue']:<12.2f}")
# 计算总体统计
total_revenue = sum(stats['total_revenue'] for stats in product_stats.values())
total_quantity = sum(stats['total_quantity'] for stats in product_stats.values())
print("-" * 35)
print(f"{'总计':<12} {total_quantity:<8} {total_revenue:<12.2f}")
analyze_sales_data()
# 游戏开发示例
def game_development_demo():
print("\n=== 游戏开发示例 ===")
import random
class TicTacToe:
def __init__(self):
self.board = [[' ' for _ in range(3)] for _ in range(3)]
self.current_player = 'X'
self.winner = None
def display_board(self):
print("\n 0 1 2")
for i in range(3):
print(f"{i} " + "|".join(self.board[i]))
if i < 2:
print(" -----")
def make_move(self, row, col):
if (0 <= row < 3 and 0 <= col < 3 and
self.board[row][col] == ' ' and self.winner is None):
self.board[row][col] = self.current_player
if self.check_winner():
self.winner = self.current_player
else:
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False
def check_winner(self):
# 检查行
for row in self.board:
if row[0] != ' ' and row[0] == row[1] == row[2]:
return True
# 检查列
for col in range(3):
if (self.board[0][col] != ' ' and
self.board[0][col] == self.board[1][col] == self.board[2][col]):
return True
# 检查对角线
if (self.board[0][0] != ' ' and
self.board[0][0] == self.board[1][1] == self.board[2][2]):
return True
if (self.board[0][2] != ' ' and
self.board[0][2] == self.board[1][1] == self.board[2][0]):
return True
return False
def is_board_full(self):
for row in self.board:
if ' ' in row:
return False
return True
def play(self):
print("井字棋游戏开始!")
print("玩家 X vs 玩家 O")
while self.winner is None and not self.is_board_full():
self.display_board()
print(f"\n当前玩家: {self.current_player}")
try:
row = int(input("请输入行号 (0-2): "))
col = int(input("请输入列号 (0-2): "))
if self.make_move(row, col):
continue
else:
print("无效移动,请重试!")
except ValueError:
print("请输入有效的数字!")
self.display_board()
if self.winner:
print(f"\n游戏结束!玩家 {self.winner} 获胜!")
else:
print("\n游戏结束!平局!")
# 启动游戏(注释掉以避免实际运行)
# game = TicTacToe()
# game.play()
print("井字棋游戏代码已准备就绪(取消注释即可运行)")
if __name__ == "__main__":
conditional_statements_demo()
loop_statements_demo()
control_statements_demo()
nested_loops_demo()
game_development_demo()
1.6 附:特性
01.Python 语言特性
a.动态类型
Python 是动态类型语言,变量类型在运行时确定,不需要提前声明类型。
-----------------------------------------------------------------------------------------------------
特点:
- 变量声明时无需指定类型
- 同一变量可以指向不同类型的对象
- 类型检查在运行时进行
-----------------------------------------------------------------------------------------------------
示例:
x = 10 # x 是整数
print(type(x)) # <class 'int'>
x = "hello" # x 现在是字符串
print(type(x)) # <class 'str'>
x = [1, 2, 3] # x 现在是列表
print(type(x)) # <class 'list'>
-----------------------------------------------------------------------------------------------------
优势:
- 代码简洁灵活
- 开发效率高
- 便于快速原型开发
-----------------------------------------------------------------------------------------------------
注意事项:
- 类型错误在运行时才会发现
- IDE 类型提示支持相对较弱
- 需要良好的测试覆盖率
b.强类型
Python 是强类型语言,不支持隐式类型转换(除数值类型外)。
-----------------------------------------------------------------------------------------------------
特点:
- 不同类型之间不能直接运算
- 需要显式类型转换
- 类型安全,避免意外错误
-----------------------------------------------------------------------------------------------------
示例:
# 数值类型间的自动转换(特殊情况)
result = 3 + 4.5 # int 转 float,结果为 7.5
# 不同类型需要显式转换
# text = "hello" + 5 # TypeError: can only concatenate str (not "int") to str
text = "hello" + str(5) # 正确:显式转换
# 布尔运算中的类型检查
# result = "10" * 2 # TypeError: can't multiply sequence by non-int of type 'str'
result = int("10") * 2 # 正确:先转换类型
# 列表操作需要类型一致
numbers = [1, 2, 3]
# numbers.append("4") # 虽然可以添加,但不推荐混合类型
numbers.append(int("4")) # 保持类型一致性
c.解释型语言
Python 代码通过解释器逐行执行,无需编译成机器码。
-----------------------------------------------------------------------------------------------------
特点:
- 代码直接运行,无需编译步骤
- 跨平台性强
- 开发调试方便
-----------------------------------------------------------------------------------------------------
执行过程:
1. 源代码 → 词法分析 → 语法分析 → AST(抽象语法树)
2. AST → 字节码编译 → 字节码
3. 字节码 → Python 虚拟机执行 → 结果
-----------------------------------------------------------------------------------------------------
示例:
# test.py 文件
def greet(name):
print(f"Hello, {name}!")
greet("Python")
# 直接运行
# python test.py
# 交互式执行
# >>> def greet(name):
# ... print(f"Hello, {name}!")
# >>> greet("Python")
# Hello, Python!
-----------------------------------------------------------------------------------------------------
优势:
- 快速开发,无需编译等待
- 动态加载模块,运行时修改
- 调试信息丰富
-----------------------------------------------------------------------------------------------------
缺点:
- 执行速度相对较慢
- 源代码容易泄露
d.缩进语法
Python 使用缩进来定义代码块,而非大括号或关键字。
-----------------------------------------------------------------------------------------------------
特点:
- 强制代码格式化
- 增强代码可读性
- 避免格式混乱
-----------------------------------------------------------------------------------------------------
缩进规则:
- 使用4个空格作为标准缩进(PEP 8)
- 同一代码块的缩进必须一致
- 不能混用空格和制表符
-----------------------------------------------------------------------------------------------------
示例:
def function_example():
if True:
print("第一层缩进")
if True:
print("第二层缩进")
for i in range(3):
print(f"第三层缩进: {i}")
print("回到第一层缩进")
class ClassExample:
def method1(self):
print("方法缩进")
def method2(self):
if True:
print("条件缩进")
else:
print("else缩进")
# 错误示例
def wrong_indentation():
print("没有缩进") # IndentationError
def mixed_indentation():
print("4个空格")
print("2个空格") # 缩进不一致
-----------------------------------------------------------------------------------------------------
优势:
- 代码格式统一
- 强制提高可读性
- 减少无意义的语法字符
-----------------------------------------------------------------------------------------------------
注意事项:
- 编辑器配置很重要
- 团队协作需要统一规范
- 复制代码时注意缩进问题
e.一切皆对象
Python 中所有数据类型都是对象,包括基本数据类型。
-----------------------------------------------------------------------------------------------------
特点:
- 每个对象都有类型、值和身份
- 对象都有属性和方法
- 支持面向对象编程
-----------------------------------------------------------------------------------------------------
对象属性:
- type(): 对象类型
- id(): 对象身份(内存地址)
- 属性和方法
-----------------------------------------------------------------------------------------------------
示例:
# 数字是对象
num = 42
print(type(num)) # <class 'int'>
print(id(num)) # 内存地址
print(num.__add__(5)) # 47,使用加法方法
# 字符串是对象
text = "hello"
print(text.upper()) # "HELLO"
print(len(text)) # 5
# 函数是对象
def my_function():
return "Hello"
print(my_function.__name__) # "my_function"
my_function.description = "This is a function"
print(hasattr(my_function, 'description')) # True
# 类是对象
class MyClass:
def __init__(self, value):
self.value = value
print(type(MyClass)) # <class 'type'>
print(MyClass.__name__) # "MyClass"
# 基本操作都是方法调用
# a + b 实际上是 a.__add__(b)
# len(a) 实际上是 a.__len__()
# a[i] 实际上是 a.__getitem__(i)
02.Python 设计哲学
a.The Zen of Python
Python 的设计哲学由 Tim Peters 总结,体现了 Python 的核心价值观。
-----------------------------------------------------------------------------------------------------
获取方式:
import this
The Zen of Python 完整内容:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
03.Python 版本
a.Python 2 vs Python 3
Python 2 和 Python 3 有重大差异,Python 2 已于2020年停止维护。
主要差异:
1. print 语句
# Python 2
print "Hello", "World"
# Python 3
print("Hello", "World")
2. 整数除法
# Python 2
5 / 2 = 2
5.0 / 2 = 2.5
# Python 3
5 / 2 = 2.5
5 // 2 = 2
3. 字符串处理
# Python 2
str = "bytes string"
unicode = u"unicode string"
# Python 3
str = "unicode string"
bytes = b"bytes string"
4. xrange 和 range
# Python 2
range(1000000) # 创建列表,占用大量内存
xrange(1000000) # 创建生成器,节省内存
# Python 3
range(1000000) # 创建range对象,节省内存
# xrange 不存在
5. 异常处理
# Python 2
except ValueError, e:
print e
# Python 3
except ValueError as e:
print(e)
6. 字典方法
# Python 2
dict.keys() # 返回列表
dict.items() # 返回列表
dict.values() # 返回列表
# Python 3
dict.keys() # 返回视图
dict.items() # 返回视图
dict.values() # 返回视图
7. input 和 raw_input
# Python 2
input() # 执行输入的代码
raw_input() # 返回字符串
# Python 3
input() # 返回字符串(类似 raw_input)
eval(input()) # 类似原来的 input()
8. 比较运算
# Python 2
1 < "" < 2 # True,可以比较不同类型
# Python 3
1 < "" # TypeError,不能比较不同类型
迁移工具:
- 2to3: Python 2 到 Python 3 的代码转换工具
- six: Python 2/3 兼容性库
- future: Python 3 移植支持
选择版本的建议:
- 新项目:使用 Python 3
- 维护项目:逐步迁移到 Python 3
- 学习:直接学习 Python 3
b.当前版本
Python 版本发布计划和特点:
Python 3 系列重要版本:
1. Python 3.0 (2008)
- 重启版本,不向后兼容
- 引入大量新特性
2. Python 3.6 (2016)
- 字典保持插入顺序
- f-string 字符串格式化
- 变量注解
3. Python 3.7 (2018)
- 数据类 (dataclasses)
- 延迟注解评估
- 时间精度纳秒
4. Python 3.8 (2019)
- 海象操作符 :=
- 位置参数
- f-string 调试
5. Python 3.9 (2020)
- 字典合并操作符
- 类型提示改进
- 字符串方法增强
6. Python 3.10 (2021)
- 结构化模式匹配
- 上下文管理器改进
- 错误消息优化
7. Python 3.11 (2022)
- 性能显著提升
- 异常组
- 类型变量
8. Python 3.12 (2023)
- 更好的性能
- f-string 改进
- Linux perf 分析
版本选择建议:
- 生产环境:使用最新的稳定版本
- 学习环境:使用 Python 3.8+ (推荐 3.11+)
- 特殊需求:根据第三方库兼容性选择
检查版本:
# 命令行
python --version
python3 --version
# Python 代码中
import sys
print(sys.version)
print(sys.version_info)
04.代码示例
# Python 语言特性演示
def python_language_features_demo():
print("=== Python 语言特性演示 ===")
# 动态类型演示
print("\n1. 动态类型:")
variable = 42
print(f"变量初始值: {variable}, 类型: {type(variable)}")
variable = "Hello Python"
print(f"变量新值: {variable}, 类型: {type(variable)}")
variable = [1, 2, 3, 4]
print(f"变量最新值: {variable}, 类型: {type(variable)}")
# 强类型演示
print("\n2. 强类型:")
try:
result = "hello" + 5
except TypeError as e:
print(f"类型错误: {e}")
# 正确的类型转换
result = "hello" + str(5)
print(f"正确转换: {result}")
# 数值类型间的隐式转换
numeric_result = 3 + 4.5
print(f"数值隐式转换: {numeric_result} (类型: {type(numeric_result)})")
# 解释型语言演示
print("\n3. 解释型语言特性:")
code = """
x = 10
y = 20
result = x + y
print(f"动态执行结果: {result}")
"""
exec(code)
# 缩进语法演示
print("\n4. 缩进语法:")
def demonstrate_indentation():
if True:
print(" 第一层缩进")
if True:
print(" 第二层缩进")
for i in range(2):
print(f" 第三层缩进: {i}")
demonstrate_indentation()
# 一切皆对象演示
print("\n5. 一切皆对象:")
# 数字对象
number = 42
print(f"数字对象: {number}")
print(f" 类型: {type(number)}")
print(f" 身份: {id(number)}")
print(f" 位长度: {number.bit_length()}")
# 字符串对象
text = "Python"
print(f"字符串对象: {text}")
print(f" 类型: {type(text)}")
print(f" 大写: {text.upper()}")
print(f" 长度: {len(text)}")
# 函数对象
def my_function():
"""示例函数"""
return "Hello from function"
print(f"函数对象: {my_function}")
print(f" 名称: {my_function.__name__}")
print(f" 文档: {my_function.__doc__}")
print(f" 调用结果: {my_function()}")
# 为函数添加属性
my_function.version = "1.0"
my_function.author = "Python Demo"
print(f" 版本: {my_function.version}")
print(f" 作者: {my_function.author}")
# Python 设计哲学演示
def python_zen_demo():
print("\n=== Python 设计哲学演示 ===")
# 导入 The Zen of Python
print("\nThe Zen of Python:")
try:
import this
except ImportError:
# 如果无法导入 this,打印部分内容
zen_lines = [
"Beautiful is better than ugly.",
"Explicit is better than implicit.",
"Simple is better than complex.",
"Readability counts."
]
for line in zen_lines:
print(f" {line}")
# 明确胜于隐含
print("\n明确胜于隐含的例子:")
# 不明确的写法
def bad_example(data):
return [x*2 for x in data if x > 0]
# 明确的写法
def good_example(data_list):
"""将列表中的正数乘以2"""
positive_numbers = [x for x in data_list if x > 0]
doubled_numbers = [x * 2 for x in positive_numbers]
return doubled_numbers
test_data = [1, -2, 3, -4, 5]
print(f" 数据: {test_data}")
print(f" 不明确写法结果: {bad_example(test_data)}")
print(f" 明确写法结果: {good_example(test_data)}")
# 简单胜于复杂
print("\n简单胜于复杂的例子:")
# 复杂写法
def complex_find_max(numbers):
max_val = float('-inf')
for i, num in enumerate(numbers):
if num > max_val:
max_val = num
max_index = i
return max_val, max_index
# 简单写法
def simple_find_max(numbers):
max_val = max(numbers)
max_index = numbers.index(max_val)
return max_val, max_index
numbers = [3, 1, 4, 1, 5, 9, 2]
print(f" 数字列表: {numbers}")
print(f" 复杂写法: {complex_find_max(numbers)}")
print(f" 简单写法: {simple_find_max(numbers)}")
# 可读性演示
print("\n可读性演示:")
# 可读性差的代码
def bad_readability(a, b, c, d, e):
return (a+b+c)*(d+e)
# 可读性好的代码
def good_readability(part1, part2, part3, part4, part5):
"""计算三部分和乘以后两部分和"""
first_group_sum = part1 + part2 + part3
second_group_sum = part4 + part5
return first_group_sum * second_group_sum
result1 = bad_readability(1, 2, 3, 4, 5)
result2 = good_readability(1, 2, 3, 4, 5)
print(f" 结果相同: {result1} == {result2}")
print(" 但第二个函数更易读和理解")
# Python 版本特性演示
def python_version_features_demo():
print("\n=== Python 版本特性演示 ===")
import sys
print(f"当前 Python 版本: {sys.version}")
print(f"版本信息: {sys.version_info}")
# 检查版本特性
version_info = sys.version_info
# f-string (Python 3.6+)
if version_info >= (3, 6):
print("\n f-string 特性 (3.6+):")
name = "Python"
version = 3.11
message = f"欢迎使用 {name} {version}"
print(f" {message}")
# f-string 表达式
x, y = 10, 20
print(f" {x} + {y} = {x + y}")
else:
print("\n 使用 format() 方法 (3.6-):")
name = "Python"
version = 3.5
message = "欢迎使用 {} {}".format(name, version)
print(f" {message}")
# 海象操作符 (Python 3.8+)
if version_info >= (3, 8):
print("\n 海象操作符 (3.8+):")
# 传统写法
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
if n > 3:
squares.append(n * n)
print(f" 传统写法: {squares}")
# 海象操作符写法
squares_new = [n*n for n in numbers if (n_squared := n*n) > 9]
print(f" 海象操作符: {squares_new}")
# 字典合并 (Python 3.9+)
if version_info >= (3, 9):
print("\n 字典合并操作符 (3.9+):")
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged = dict1 | dict2
print(f" 字典1: {dict1}")
print(f" 字典2: {dict2}")
print(f" 合并结果: {merged}")
else:
print("\n 传统字典合并 (3.9-):")
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged = {**dict1, **dict2}
print(f" 合并结果: {merged}")
# 模式匹配 (Python 3.10+)
if version_info >= (3, 10):
print("\n 结构化模式匹配 (3.10+):")
def process_data(data):
match data:
case {'type': 'number', 'value': n}:
return f"数字: {n}"
case {'type': 'text', 'content': s}:
return f"文本: {s}"
case {'type': 'list', 'items': lst}:
return f"列表: {lst}"
case _:
return "未知数据类型"
data_samples = [
{'type': 'number', 'value': 42},
{'type': 'text', 'content': 'Hello'},
{'type': 'list', 'items': [1, 2, 3]}
]
for data in data_samples:
result = process_data(data)
print(f" {result}")
# 综合特性演示
def comprehensive_features_demo():
print("\n=== 综合特性演示 ===")
# 创建一个类来演示面向对象特性
class PythonDemonstration:
"""Python 特性演示类"""
# 类变量
species = "Python Programming Language"
def __init__(self, version):
# 实例变量
self.version = version
self.features = []
def add_feature(self, feature):
"""添加特性"""
self.features.append(feature)
return f"已添加特性: {feature}"
def show_features(self):
"""显示所有特性"""
if not self.features:
return "暂无特性"
return "\n".join(f"- {feature}" for feature in self.features)
def __str__(self):
"""字符串表示"""
return f"{self.species} v{self.version}"
def __len__(self):
"""长度表示"""
return len(self.features)
# 创建实例
python_demo = PythonDemonstration("3.11")
# 添加特性
features_to_add = [
"动态类型系统",
"强类型检查",
"解释型执行",
"缩进语法结构",
"一切皆对象"
]
print(f"创建: {python_demo}")
print(f"特性数量: {len(python_demo)}")
for feature in features_to_add:
result = python_demo.add_feature(feature)
print(f" {result}")
print(f"\n{python_demo} 特性列表:")
print(python_demo.show_features())
print(f"\n最终特性数量: {len(python_demo)}")
# 演示动态性
print("\n动态性演示:")
print(f"原始版本: {python_demo.version}")
# 动态添加属性
python_demo.release_year = 1991
python_demo.creator = "Guido van Rossum"
print(f"动态添加属性 - 发布年份: {python_demo.release_year}")
print(f"动态添加属性 - 创作者: {python_demo.creator}")
# 动态添加方法
def get_age(self):
"""计算语言年龄"""
from datetime import datetime
return datetime.now().year - self.release_year
# 将方法绑定到实例
python_demo.get_age = get_age.__get__(python_demo, PythonDemonstration)
print(f"动态添加方法 - 年龄: {python_demo.get_age()} 岁")
# 演示内存管理
print("\n内存管理演示:")
import gc
# 创建一些对象
objects = []
for i in range(1000):
objects.append(f"object_{i}")
print(f"创建了 {len(objects)} 个对象")
# 删除引用
del objects
print("删除对象引用")
# 强制垃圾回收
collected = gc.collect()
print(f"垃圾回收清理了 {collected} 个对象")
if __name__ == "__main__":
python_language_features_demo()
python_zen_demo()
python_version_features_demo()
comprehensive_features_demo()
1.7 附:命令
00.Python 解释器
a.交互式环境
Python 提供了强大的交互式环境,支持实时代码执行和调试。
-----------------------------------------------------------------------------------------------------
启动交互式环境:
# Windows
python
python -i script.py
# Linux/macOS
python3
python3 -i script.py
-----------------------------------------------------------------------------------------------------
基本交互式操作:
>>> print("Hello, World!")
Hello, World!
>>> x = 10
>>> y = 20
>>> x + y
30
>>> import math
>>> math.sqrt(16)
4.0
-----------------------------------------------------------------------------------------------------
交互式环境特性:
- 实时代码执行
- 自动补全(Tab 键)
- 历史记录(上下箭头)
- 变量状态保持
- 内置帮助系统
-----------------------------------------------------------------------------------------------------
内置帮助:
>>> help(len)
>>> help(str.upper)
-----------------------------------------------------------------------------------------------------
退出交互式环境:
>>> exit()
>>> quit()
# 或者按 Ctrl+D (Linux/macOS) / Ctrl+Z 然后 Enter (Windows)
-----------------------------------------------------------------------------------------------------
IPython 增强:
# 安装 IPython
pip install ipython
# 启动 IPython
ipython
-----------------------------------------------------------------------------------------------------
IPython 特性:
- 更好的语法高亮
- 魔法命令 (%run, %timeit 等)
- 内置 Shell 命令
- 对象检查和调试
- 丰富的扩展生态
-----------------------------------------------------------------------------------------------------
示例:
In [1]: %timeit [x**2 for x in range(1000)]
1000 loops, best of 3: 243 µs per loop
In [2]: !ls
file1.py file2.py README.md
b.脚本执行
Python 脚本可以直接从命令行执行。
-----------------------------------------------------------------------------------------------------
基本执行:
# 执行 Python 脚本
python script.py
# 使用绝对路径
python /path/to/script.py
# 使用相对路径
python ./script.py
-----------------------------------------------------------------------------------------------------
脚本参数:
# script.py
import sys
print(f"脚本名称: {sys.argv[0]}")
print(f"参数数量: {len(sys.argv) - 1}")
for i, arg in enumerate(sys.argv[1:], 1):
print(f"参数 {i}: {arg}")
# 命令行执行
python script.py arg1 arg2 arg3
-----------------------------------------------------------------------------------------------------
# 输出
# 脚本名称: script.py
# 参数数量: 3
# 参数 1: arg1
# 参数 2: arg2
# 参数 3: arg3
-----------------------------------------------------------------------------------------------------
常用执行选项:
# 显示 Python 版本
python --version
python -V
# 详细执行
python -v script.py # 显示导入的模块
python -vv script.py # 更详细的信息
# 调试模式
python -m pdb script.py # 使用 pdb 调试器
# 性能分析
python -m cProfile script.py
# 内存分析(需要安装 memory_profiler)
python -m memory_profiler script.py
# 设置编码
python -X utf8 script.py # Python 3.7+
# 不显示欢迎信息
python -q script.py
# 警告控制
python -W all script.py # 显示所有警告
python -W ignore script.py # 忽略警告
标准输入输出重定向:
# 输入重定向
python script.py < input.txt
# 输出重定向
python script.py > output.txt
# 错误重定向
python script.py 2> error.log
# 同时重定向
python script.py > output.txt 2>&1
管道操作:
# 与其他命令组合
python script.py | grep "error"
# 管道输入
echo "hello" | python script.py
c.字节码编译
Python 可以将源代码编译成字节码,提高加载速度。
自动编译:
# Python 会自动创建 .pyc 文件
script.py → script.pyc # 编译后的字节码
# 字节码文件位置
__pycache__/
├── script.cpython-311.pyc
└── module.cpython-311.pyc
手动编译:
# 编译单个文件
python -m py_compile script.py
# 编译目录
python -m compileall .
python -m compileall /path/to/directory
# 优化级别
python -O -m py_compile script.py # 优化级别 1 (.pyo)
python -OO -m py_compile script.py # 优化级别 2 (移除断言和文档字符串)
编译选项:
# py_compile 模块选项
python -m py_compile -q script.py # 静默模式
python -m py_compile -f script.py # 强制重新编译
# compileall 模块选项
python -m compileall -q . # 静默编译目录
python -m compileall -f . # 强制重新编译
python -m compileall -j 4 . # 使用 4 个并行进程
字节码工具:
# 查看字节码
python -c "import dis; dis.dis(open('script.py').read())"
# 查看编译时间戳
python -c "import py_compile; py_compile.compile('script.py')"
清理编译文件:
# 删除 __pycache__ 目录
find . -name "__pycache__" -type d -exec rm -rf {} +
# 删除所有 .pyc 文件
find . -name "*.pyc" -delete
# 使用 pyclean 工具
pip install pyclean
pyclean .
01.pip 包管理
a.安装包
pip 是 Python 的标准包管理工具,用于安装和管理第三方包。
基本安装:
# 安装最新版本
pip install package_name
# 安装指定版本
pip install package_name==1.2.3
pip install package_name>=1.0.0,<2.0.0
# 从 requirements.txt 安装
pip install -r requirements.txt
安装源选项:
# 从 PyPI(默认)
pip install requests
# 从 Git 仓库
pip install git+https://github.com/user/repo.git
pip install git+https://github.com/user/repo.git@branch
pip install git+https://github.com/user/repo.git#subdirectory=subpackage
# 从本地目录
pip install ./local_package
pip install /path/to/local_package
# 从 URL
pip install https://example.com/package.tar.gz
开发模式安装:
# 可编辑安装(用于开发)
pip install -e .
pip install -e /path/to/package
安装选项:
# 升级包
pip install --upgrade package_name
pip install -U package_name
# 强制重新安装
pip install --force-reinstall package_name
pip install --ignore-installed package_name
# 仅考虑已缓存的文件
pip install --no-cache-dir package_name
# 使用特定索引源
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ package_name
# 用户安装(仅当前用户)
pip install --user package_name
# 安装到特定目录
pip install -t /path/to/directory package_name
# 安装依赖但不安装包本身
pip install --no-deps package_name
# 安装编译依赖
pip install --install-option="--install-scripts=/usr/local/bin" package_name
系统包安装:
# Ubuntu/Debian
sudo apt install python3-pip
sudo pip3 install package_name
# CentOS/RHEL
sudo yum install python3-pip
sudo pip3 install package_name
# Windows 管理员权限
pip install package_name
b.卸载包
安全地移除不需要的包及其依赖。
基本卸载:
# 卸载包
pip uninstall package_name
# 卸载多个包
pip uninstall package1 package2 package3
# 卸载时不确认
pip uninstall -y package_name
卸载选项:
# 卸载但保留配置文件
pip uninstall package_name --keep-config
# 清理缓存
pip cache purge
# 卸载及其依赖
pip uninstall package_name --yes
批量卸载:
# 从文件卸载
pip uninstall -r requirements.txt
# 卸载所有用户安装的包
pip list --user | cut -d' ' -f1 | xargs pip uninstall -y
安全卸载:
# 检查包的依赖关系
pip show package_name
pip list | grep package_name
# 查看哪些包依赖该包
pip package_name
c.查看已安装包
了解和管理系统中已安装的 Python 包。
列出已安装包:
# 基本列表
pip list
# 过时包列表
pip list --outdated
# 用户安装包
pip list --user
# 格式化输出
pip list --format=columns
pip list --format=freeze
pip list --format=json
包信息查看:
# 显示包详细信息
pip show package_name
pip show -f package_name # 显示文件列表
# 查看包依赖
pip show --requires package_name
pip depends package_name # 需要 pipdeptree
# 查找包
pip search keyword # PyPI 搜索(可能已禁用)
版本检查:
# 检查可更新包
pip list --outdated
# 检查特定包版本
pip show package_name | grep Version
# 比较版本
python -c "import package_name; print(package_name.__version__)"
依赖分析:
# 安装依赖分析工具
pip install pipdeptree
# 查看依赖树
pipdeptree
# 查看反向依赖
pipdeptree -r -p package_name
# 冲突检查
pip check
缓存管理:
# 查看缓存信息
pip cache info
# 列出缓存文件
pip cache list
# 清理缓存
pip cache purge
pip cache remove package_name
d.requirements.txt
项目的依赖管理文件,用于重现环境。
创建 requirements.txt:
# 从当前环境创建
pip freeze > requirements.txt
# 只包括直接依赖
pip install pipreqs
pipreqs . --encoding=utf8
# 手动创建文件
touch requirements.txt
requirements.txt 格式:
# 基本格式
requests==2.28.1
numpy>=1.21.0,<2.0.0
flask==2.2.2
# 不指定版本(最新)
django
# 版本范围
pandas>=1.3.0
matplotlib~=3.5.0 # 等价于 >=3.5.0, <3.6.0
# 从 Git 安装
git+https://github.com/user/repo.git@v1.0.0#egg=package
# 本地路径
./local_package
-e ./editable_package
# 附加索引
--extra-index-url https://pypi.org/simple
-i https://pypi.tuna.tsinghua.edu.cn/simple/
注释和分组:
# Web 框架
django==4.1.0
flask==2.2.2
# 数据处理
pandas==1.4.0
numpy==1.21.0
# 开发工具(可选)
# pytest==7.1.0
# black==22.6.0
环境分离:
# requirements/base.txt
django>=4.0
requests>=2.25.0
# requirements/dev.txt
-r base.txt
pytest>=6.0
black>=22.0
# requirements/prod.txt
-r base.txt
gunicorn>=20.0
# 安装特定环境的依赖
pip install -r requirements/dev.txt
最佳实践:
1. 使用精确版本号保证一致性
2. 分离开发和生产依赖
3. 定期更新依赖
4. 使用虚拟环境隔离依赖
02.虚拟环境
a.venv 创建虚拟环境
venv 是 Python 3.3+ 内置的虚拟环境创建工具。
创建虚拟环境:
# 基本创建
python -m venv myenv
# 指定 Python 版本
python3.9 -m venv myenv
/usr/bin/python3.8 -m venv myenv
# 不包含 site-packages
python -m venv --system-site-packages myenv
# 指定目录
python -m venv /path/to/myenv
venv 选项:
# 清晰模式(默认)
python -m venv myenv
# 系统站点包
python -m venv --system-site-packages myenv
# 可写系统站点包
python -m venv --copies myenv
# 使用符号链接
python -m venv --symlinks myenv
# 清除现有环境
python -m venv --clear myenv
# 升级环境
python -m venv --upgrade myenv
项目结构:
myproject/
├── myenv/ # 虚拟环境目录
│ ├── Include/ # 头文件
│ ├── Lib/ # Python 库
│ ├── Scripts/ # 可执行文件 (Windows)
│ ├── bin/ # 可执行文件 (Linux/macOS)
│ └── pyvenv.cfg # 配置文件
├── src/
└── requirements.txt
配置文件 (pyvenv.cfg):
home = /usr/bin
implementation = CPython
version_info = 3.11.0.final.0
executable = /usr/bin/python3
include-system-site-packages = false
多版本管理:
# 为不同 Python 版本创建环境
python3.8 -m venv env38
python3.9 -m venv env39
python3.10 -m venv env310
python3.11 -m venv env311
# 环境命名规范
venv-{python_version}
{project_name}-env
.venv (隐藏目录)
b.激活虚拟环境
激活虚拟环境后,命令行提示符会变化,Python 和 pip 命令会指向虚拟环境。
Windows 激活:
# CMD
myenv\Scripts\activate.bat
# PowerShell
myenv\Scripts\Activate.ps1
# Git Bash
source myenv/Scripts/activate
Linux/macOS 激活:
# Bash/Zsh
source myenv/bin/activate
# Fish
source myenv/bin/activate.fish
# CSH
source myenv/bin/activate.csh
激活后的变化:
# 命令行提示符变化
(myenv) user@host:~$
# Python 版本
(myenv) $ python --version
Python 3.11.0
# pip 路径
(myenv) $ which pip
/path/to/myenv/bin/pip
# 包安装位置
(myenv) $ python -c "import site; print(site.getsitepackages())"
['/path/to/myenv/lib/python3.11/site-packages']
环境变量:
# 查看环境变量
(myenv) $ echo $VIRTUAL_ENV
/path/to/myenv
(myenv) $ echo $PATH
/path/to/myenv/bin:/usr/bin:/bin
# Python 路径
(myenv) $ which python
/path/to/myenv/bin/python
验证激活:
# 检查 Python 版本和位置
python -c "import sys; print(sys.executable)"
# 检查已安装包
pip list
# 检查包路径
python -c "import site; print(site.getsitepackages())"
c.退出虚拟环境
简单地返回到全局 Python 环境。
退出命令:
# 通用方法
deactivate
# 自动退出(脚本中)
#!/bin/bash
source myenv/bin/activate
python script.py
deactivate
# PowerShell 退出
deactivate
# 批处理文件退出
call myenv\Scripts\activate.bat
python script.py
call myenv\Scripts\deactivate.bat
退出后的状态:
# 提示符恢复
user@host:~$
# Python 回到全局版本
$ python --version
Python 3.8.10 # 系统全局版本
# pip 回到全局版本
$ which pip
/usr/bin/pip
清理虚拟环境:
# 完全删除虚拟环境
rm -rf myenv/
# Windows
rmdir /s myenv
# 批量清理(查找所有虚拟环境)
find . -name "pyvenv.cfg" -exec dirname {} \; | xargs rm -rf
03.常用命令
a.开发工具命令
常用的 Python 开发和调试命令。
代码格式化:
# black 代码格式化
pip install black
black script.py
black --line-length 80 src/
black --check src/
# autopep8 格式化
pip install autopep8
autopep8 --in-place --aggressive --aggressive script.py
# isort 导入排序
pip install isort
isort script.py
isort --profile black src/
代码检查:
# flake8 代码检查
pip install flake8
flake8 script.py
flake8 --max-line-length=88 src/
# pylint 代码分析
pip install pylint
pylint script.py
pylint --disable=C0111 src/
# mypy 类型检查
pip install mypy
mypy script.py
mypy --ignore-missing-imports src/
测试命令:
# pytest 测试框架
pip install pytest
pytest
pytest -v test_module.py
pytest --cov=src tests/
# unittest 标准测试
python -m unittest
python -m unittest test_module
python -m unittest test_module.TestClass.test_method
# doctest 文档测试
python -m doctest script.py
python -m doctest -v script.py
调试命令:
# pdb 调试器
python -m pdb script.py
python -c "import pdb; pdb.run('script.main()')"
# ipdb 增强调试器
pip install ipdb
python -m ipdb script.py
# cProfile 性能分析
python -m cProfile script.py
python -m cProfile -s time script.py
# memory_profiler 内存分析
pip install memory_profiler
python -m memory_profiler script.py
b.项目构建命令
项目打包和分发相关命令。
setuptools 打包:
# 安装构建工具
pip install setuptools wheel build
# 构建分发包
python -m build
# 本地安装
pip install .
# 开发模式安装
pip install -e .
# 上传到 PyPI
pip install twine
python -m twine upload dist/*
Poetry 包管理:
# 安装 Poetry
curl -sSL https://install.python-poetry.org | python3 -
# 初始化项目
poetry init
poetry new project_name
# 依赖管理
poetry add requests
poetry add --group dev pytest
poetry remove requests
# 环境管理
poetry env use python3.11
poetry shell
poetry run python script.py
# 构建
poetry build
Docker 构建:
# Dockerfile 示例
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
# 构建和运行
docker build -t myapp .
docker run -p 8000:8000 myapp
c.系统命令
Python 系统级别的常用命令。
模块管理:
# 查看模块位置
python -c "import sys; print(sys.path)"
# 重新加载模块
python -c "import importlib; importlib.reload(module_name)"
# 列出已安装模块
help('modules')
# 模块搜索路径
python -c "import os; print(os.__file__)"
环境信息:
# Python 版本信息
python --version
python -V
python -c "import sys; print(sys.version)"
# 实现信息
python -c "import sys; print(sys.implementation)"
# 平台信息
python -c "import platform; print(platform.platform())"
# 编译器信息
python -c "import sys; print(sys.version)"
性能相关:
# 启动时间测量
python -X timeit -c "code"
# 内存使用
python -c "import psutil; print(psutil.virtual_memory())"
# CPU 信息
python -c "import platform; print(platform.processor())"
文件操作:
# 编译 Python 文件
python -m compileall .
python -m py_compile script.py
# 生成字节码
python -m py_compile -o . script.py
# 查看字节码
python -m dis script.py
安全相关:
# 安全审计
pip install bandit
bandit -r src/
# 依赖安全检查
pip install safety
safety check
# 许可证检查
pip install pip-licenses
pip-licenses --from=mixed
1.8 附:路线图
01.Python 简介
a.概念
Python 是一种高级编程语言,由 Guido van Rossum 于 1989 年发明,1991 年首次发布。
Python 的设计哲学强调代码的可读性和简洁性,特别是使用空格缩进来划分代码块。
-----------------------------------------------------------------------------------------------------
核心特征:
- 解释型语言:代码不需要编译,直接由解释器执行
- 动态类型:变量类型在运行时确定,无需提前声明
- 强类型:类型检查严格,不支持隐式类型转换
- 面向对象:支持面向对象编程范式
- 多范式:支持面向对象、函数式、过程式编程
-----------------------------------------------------------------------------------------------------
语言特点:
- 语法简洁清晰,接近自然语言
- 丰富的标准库和第三方库
- 跨平台:Windows、Linux、macOS 等系统
- 开源免费:遵循 PSF 许可证
- 活跃的社区支持
b.发展历史
Python 的发展历程经历了多个重要版本:
-----------------------------------------------------------------------------------------------------
早期阶段(1989-2000):
- 1989年:Guido van Rossum 在荷兰开始开发 Python
- 1991年:Python 0.9.0 发布,在 Usenet 上公开
- 1994年:Python 1.0 发布
- 2000年:Python 2.0 发布,引入列表推导式、垃圾回收改进
-----------------------------------------------------------------------------------------------------
Python 2 时代(2000-2010):
- 2006年:Python 2.5 发布,引入 with 语句
- 2008年:Python 2.6 发布,引入 abc 模块、格式化字符串
- 2010年:Python 2.7 发布,成为 Python 2 的最后一个主版本
-----------------------------------------------------------------------------------------------------
Python 3 时代(2008-至今):
- 2008年:Python 3.0 发布,不向后兼容的重要版本
- 2011年:Python 3.2 发布,引入 concurrent.futures
- 2012年:Python 3.3 发布,引入 yield from、venv 虚拟环境
- 2014年:Python 3.4 发布,引入 asyncio、pip 集成
- 2015年:Python 3.5 发布,引入 async/await、类型注解
- 2016年:Python 3.6 发布,引入 f-string、字典保持顺序
- 2018年:Python 3.7 发布,引入数据类、延迟注解
- 2019年:Python 3.8 发布,引入海象操作符、位置参数
- 2020年:Python 3.9 发布,引入字典合并操作符
- 2021年:Python 3.10 发布,引入结构化模式匹配
- 2022年:Python 3.11 发布,性能显著提升
- 2023年:Python 3.12 发布,更好的性能和新特性
-----------------------------------------------------------------------------------------------------
重要里程碑:
- 2001年:Python 软件基金会(PSF)成立
- 2008年:Python 2 和 Python 3 分叉
- 2020年:Python 2 正式停止支持
- 2021年:Python 成为 TIOBE 年度编程语言
c.应用领域
Python 在多个领域都有广泛的应用:
-----------------------------------------------------------------------------------------------------
Web 开发:
- 框架:Django、Flask、FastAPI、Tornado
- 后端 API 开发
- 内容管理系统
- 微服务架构
- RESTful API 设计
-----------------------------------------------------------------------------------------------------
数据科学与人工智能:
- 数据分析:NumPy、Pandas、Matplotlib
- 机器学习:Scikit-learn、TensorFlow、PyTorch
- 深度学习:Keras、Theano
- 数据可视化:Seaborn、Plotly、Bokeh
- 自然语言处理:NLTK、spaCy、Transformers
-----------------------------------------------------------------------------------------------------
自动化与运维:
- 系统管理脚本
- 自动化测试
- 网络爬虫
- 配置管理
- DevOps 工具
-----------------------------------------------------------------------------------------------------
科学计算:
- 数值计算:SciPy
- 符号计算:SymPy
- 生物信息学:Biopython
- 天文学:Astropy
- 金融分析:QuantLib
-----------------------------------------------------------------------------------------------------
游戏开发:
- 游戏脚本
- 2D 游戏:Pygame
- 3D 图形:PyOpenGL
- 游戏引擎集成
-----------------------------------------------------------------------------------------------------
桌面应用:
- GUI 开发:Tkinter、PyQt、wxPython
- 系统工具
- 办公自动化
- 图像处理:Pillow、OpenCV
-----------------------------------------------------------------------------------------------------
教育:
- 编程入门教学
- 计算机科学教育
- 算法和数据结构教学
- 科学研究
02.Python 生态系统
a.标准库
Python 标准库是 Python 安装时自带的模块集合,提供了丰富的功能:
-----------------------------------------------------------------------------------------------------
核心模块:
- sys:系统特定参数和函数
- os:操作系统接口
- math:数学函数
- datetime:日期和时间处理
- json:JSON 数据编码解码
- re:正则表达式操作
- collections:特殊容器数据类型
- itertools:迭代工具
- functools:高阶函数和操作
-----------------------------------------------------------------------------------------------------
文件和数据处理:
- pathlib:面向对象路径操作
- csv:CSV 文件读写
- sqlite3:SQLite 数据库接口
- xml.etree.ElementTree:XML 处理
- pickle:对象序列化
- gzip/zip:文件压缩
-----------------------------------------------------------------------------------------------------
网络编程:
- socket:底层网络接口
- http.client:HTTP 客户端
- urllib:URL 处理
- email:邮件处理
- smtplib:SMTP 客户端
- ssl:TLS/SSL 支持
-----------------------------------------------------------------------------------------------------
并发和并行:
- threading:线程支持
- multiprocessing:多进程支持
- asyncio:异步 I/O
- concurrent.futures:并发执行
- queue:同步队列
- subprocess:子进程管理
-----------------------------------------------------------------------------------------------------
开发工具:
- unittest:单元测试框架
- doctest:文档测试
- pdb:调试器
- profile:性能分析
- timeit:执行时间测量
- trace:代码执行跟踪
-----------------------------------------------------------------------------------------------------
国际化和本地化:
- locale:文化相关设置
- gettext:国际化框架
- codecs:编解码器注册
- unicodedata:Unicode 数据库
-----------------------------------------------------------------------------------------------------
安全和加密:
- hashlib:安全哈希和消息摘要
- hmac:消息认证
- secrets:安全随机数生成
- ssl:TLS/SSL 包装器
b.第三方库
第三方库是 Python 强大功能的重要组成部分:
-----------------------------------------------------------------------------------------------------
数据科学栈:
- NumPy:数值计算基础库
- Pandas:数据分析和处理
- Matplotlib:数据可视化
- Seaborn:统计数据可视化
- SciPy:科学计算库
- Scikit-learn:机器学习
- Statsmodels:统计建模
-----------------------------------------------------------------------------------------------------
Web 开发:
- Django:全栈 Web 框架
- Flask:轻量级 Web 框架
- FastAPI:现代高性能 Web 框架
- Requests:HTTP 库
- BeautifulSoup:HTML/XML 解析
- Selenium:Web 自动化测试
-----------------------------------------------------------------------------------------------------
数据库:
- SQLAlchemy:ORM 框架
- psycopg2:PostgreSQL 适配器
- mysql-connector-python:MySQL 适配器
- pymongo:MongoDB 驱动
- redis:Redis 客户端
-----------------------------------------------------------------------------------------------------
自动化和系统管理:
- Fabric:远程执行和部署
- Ansible:自动化配置管理
- Celery:分布式任务队列
- APScheduler:任务调度
- watchdog:文件系统事件监控
-----------------------------------------------------------------------------------------------------
图像和多媒体:
- Pillow:图像处理
- OpenCV:计算机视觉
- MoviePy:视频编辑
- PyAudio:音频处理
-----------------------------------------------------------------------------------------------------
网络爬虫:
- Scrapy:爬虫框架
- BeautifulSoup:HTML 解析
- lxml:XML 和 HTML 解析
- Selenium:浏览器自动化
-----------------------------------------------------------------------------------------------------
测试和质量保证:
- pytest:测试框架
- coverage:代码覆盖率
- locust:负载测试
- mock:模拟对象
-----------------------------------------------------------------------------------------------------
开发工具:
- Black:代码格式化
- Flake8:代码检查
- MyPy:静态类型检查
- Jupyter Notebook:交互式计算
c.包管理
Python 的包管理生态系统:
-----------------------------------------------------------------------------------------------------
PyPI(Python Package Index):
- 官方包仓库:https://pypi.org
- 超过 40 万个包
- 包名搜索和发现
- 版本管理和发布
-----------------------------------------------------------------------------------------------------
包管理工具:
- pip:标准包管理器
- conda:跨语言包管理器(Anaconda)
- poetry:现代依赖管理
- pipenv:虚拟环境和依赖管理
- easy_install:传统包管理器
-----------------------------------------------------------------------------------------------------
虚拟环境:
- venv:标准虚拟环境工具
- virtualenv:第三方虚拟环境工具
- conda 环境:Anaconda 环境管理
- docker:容器化环境
-----------------------------------------------------------------------------------------------------
版本控制:
- 语义化版本控制(SemVer)
- 版本约束和兼容性
- 依赖解析算法
- 锁定文件(requirements.txt, Pipfile.lock)
-----------------------------------------------------------------------------------------------------
包发布:
- 打包工具:setuptools, wheel, build
- 发布工具:twine, flit
- 持续集成测试
- 文档生成
03.Python 特点
a.优势
Python 的主要优势使其成为流行的编程语言:
-----------------------------------------------------------------------------------------------------
易学易用:
- 语法简洁清晰,接近自然语言
- 代码可读性强
- 学习曲线平缓
- 丰富的学习资源
-----------------------------------------------------------------------------------------------------
开发效率高:
- 代码简洁,表达力强
- 丰富的标准库和第三方库
- 快速原型开发
- 迭代开发友好
-----------------------------------------------------------------------------------------------------
跨平台支持:
- Windows、Linux、macOS 全平台支持
- 代码无需修改即可跨平台运行
- 统一的开发体验
-----------------------------------------------------------------------------------------------------
强大的社区:
- 活跃的开发者社区
- 丰富的文档和教程
- 定期的会议和活动
- 开源文化浓厚
-----------------------------------------------------------------------------------------------------
企业级应用:
- Google、Facebook、Netflix 等大公司使用
- 成功的商业应用案例
- 完善的企业级框架和工具
- 长期支持和维护
-----------------------------------------------------------------------------------------------------
生态丰富:
- 覆盖所有主要应用领域
- 高质量的第三方库
- 活跃的包开发和维护
- 持续的技术创新
-----------------------------------------------------------------------------------------------------
集成能力:
- 与 C/C++ 扩展集成
- 与其他语言互操作
- 云平台和容器支持
- API 和微服务友好
b.适用场景
Python 适合的应用场景和典型用例:
-----------------------------------------------------------------------------------------------------
最适合的场景:
- 快速原型开发
- 数据分析和科学计算
- Web 后端开发
- 自动化脚本和工具
- 机器学习和人工智能
- 教育和培训
- API 开发
-----------------------------------------------------------------------------------------------------
不太适合的场景:
- 高性能计算(C/C++ 更合适)
- 实时系统(Rust/C++ 更合适)
- 移动应用原生开发(Java/Kotlin/Swift 更合适)
- 大型游戏引擎(C++ 更合适)
- 系统级编程(C/Rust 更合适)
-----------------------------------------------------------------------------------------------------
典型应用案例:
- Instagram:Django Web 应用
- Dropbox:桌面客户端和后端
- YouTube:部分后端服务
- Reddit:Web 平台
- Spotify:部分数据分析
- Netflix:内容推荐系统
04.Python 发展方向
a.数据科学
Python 在数据科学领域的发展趋势:
-----------------------------------------------------------------------------------------------------
核心库生态:
- NumPy:数值计算基础,持续性能优化
- Pandas:数据分析,正在重构以提高性能
- Matplotlib/Seaborn:可视化,新增现代图表类型
- Scikit-learn:机器学习,算法库持续扩展
-----------------------------------------------------------------------------------------------------
新兴技术:
- Polars:高性能 DataFrame 库
- Vaex:大数据可视化
- Dask:并行计算
- Ray:分布式计算框架
-----------------------------------------------------------------------------------------------------
深度学习:
- TensorFlow/PyTorch:主流深度学习框架
- JAX:高性能数值计算
- Hugging Face Transformers:自然语言处理
- Keras:高级神经网络 API
-----------------------------------------------------------------------------------------------------
大数据集成:
- Apache Spark:PySpark 接口
- Apache Kafka:数据流处理
- Elasticsearch:搜索和分析
- ClickHouse:列式数据库
-----------------------------------------------------------------------------------------------------
云计算支持:
- AWS/Boto3:亚马逊云服务
- Azure SDK:微软云服务
- Google Cloud:谷歌云服务
- 各大云平台的原生 Python 支持
b.Web 开发
Python Web 开发的现代趋势:
-----------------------------------------------------------------------------------------------------
现代框架:
- FastAPI:高性能异步 Web 框架
- Django:成熟的 Web 框架,持续更新
- Flask:轻量级框架,生态丰富
- Starlette:ASGI 框架基础
-----------------------------------------------------------------------------------------------------
异步编程:
- asyncio 标准库持续改进
- async/await 语法普及
- 异步数据库驱动:asyncpg, aiosqlite
- 异步 Web 服务器:Uvicorn, Hypercorn
-----------------------------------------------------------------------------------------------------
微服务架构:
- 服务间通信:gRPC, GraphQL
- API 网关:Kong, Tyk
- 服务发现:Consul, etcd
- 容器化:Docker, Kubernetes
-----------------------------------------------------------------------------------------------------
前后端分离:
- RESTful API 设计
- GraphQL API
- WebSocket 实时通信
- Serverless 函数
-----------------------------------------------------------------------------------------------------
DevOps 集成:
- CI/CD 流水线
- 容器编排
- 监控和日志
- 自动化部署
c.自动化运维
Python 在运维自动化领域的发展:
-----------------------------------------------------------------------------------------------------
基础设施即代码:
- Ansible:自动化配置管理
- Fabric:远程执行和部署
- SaltStack:基础设施管理
- Terraform:基础设施声明式管理
-----------------------------------------------------------------------------------------------------
容器化和编排:
- Docker:容器化技术
- Kubernetes:容器编排
- Helm:Kubernetes 包管理
- Docker Compose:多容器应用
-----------------------------------------------------------------------------------------------------
监控和告警:
- Prometheus:监控和告警
- Grafana:数据可视化
- ELK Stack:日志分析
- Zabbix:综合监控
-----------------------------------------------------------------------------------------------------
网络自动化:
- Netmiko:网络设备自动化
- NAPALM:网络抽象层
- Paramiko:SSH 库
- Scapy:网络包操作
-----------------------------------------------------------------------------------------------------
云原生技术:
- Serverless 函数
- 微服务架构
- 服务网格
- 云原生监控
d.人工智能
Python 在 AI 领域的领先地位:
-----------------------------------------------------------------------------------------------------
机器学习框架:
- Scikit-learn:传统机器学习
- XGBoost/LightGBM:梯度提升
- CatBoost:类别特征处理
- AutoML:自动化机器学习
-----------------------------------------------------------------------------------------------------
深度学习:
- PyTorch:研究首选框架
- TensorFlow:工业级部署
- JAX:高性能计算
- Keras:高级 API
-----------------------------------------------------------------------------------------------------
自然语言处理:
- Hugging Face Transformers:预训练模型
- spaCy:工业级 NLP
- NLTK:学术研究工具
- Gensim:主题建模
-----------------------------------------------------------------------------------------------------
计算机视觉:
- OpenCV:计算机视觉库
- Pillow:图像处理
- PyTorch Vision:计算机视觉工具包
- scikit-image:图像处理算法
-----------------------------------------------------------------------------------------------------
MLOps:
- MLflow:机器学习生命周期管理
- Kubeflow:Kubernetes 机器学习平台
- DVC:数据版本控制
- Weights & Biases:实验跟踪
-----------------------------------------------------------------------------------------------------
边缘 AI:
- ONNX:开放神经网络交换
- TensorFlow Lite:移动和边缘部署
- PyTorch Mobile:移动端支持
- TinyML:微型机器学习
2 容器
2.1 列表(List)
00.总结
a.说明
列表是Python中最常用的容器类型之一,用于存储多个有序的元素集合。
列表中的元素可以是任意类型,包括数字、字符串、对象等。
列表是可变类型,允许在创建后进行修改。
b.特点
有序序列,元素按插入顺序存储;
可变容器,支持动态添加、删除、修改元素;
异构性,可容纳不同类型的元素;
支持索引和切片操作;
可以包含重复元素;
支持嵌套,列表可以包含其他列表。
c.常用操作
创建列表:[]、list()、列表推导式;
访问元素:索引访问、切片操作;
修改元素:索引赋值、切片赋值;
添加元素:append()、extend()、insert();
删除元素:del、remove()、pop();
排序操作:sort()、sorted();
统计方法:count()、index()
01.列表创建和访问
a.创建列表
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed = [1, 'hello', 3.14, True]
list_from_string = list('hello')
list_from_range = list(range(5))
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
b.访问元素
fruits = ['apple', 'banana', 'orange', 'grape']
first = fruits[0]
last = fruits[-1]
second = fruits[1]
matrix = [[1, 2, 3], [4, 5, 6]]
element = matrix[0][1]
c.切片操作
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
first_three = numbers[0:3]
last_three = numbers[-3:]
middle = numbers[2:8]
every_second = numbers[::2]
reversed_list = numbers[::-1]
numbers[1:4] = [10, 20, 30]
numbers[::2] = [0, 0, 0, 0, 0]
02.列表修改
a.添加元素
fruits = ['apple', 'banana']
fruits.append('orange')
fruits.extend(['grape', 'kiwi'])
fruits.insert(1, 'mango')
fruits += ['peach', 'pear']
repeated = [1, 2] * 3
b.删除元素
numbers = [1, 2, 3, 4, 5]
del numbers[2]
del numbers[1:3]
fruits = ['apple', 'banana', 'apple', 'orange']
fruits.remove('apple')
last = fruits.pop()
first = fruits.pop(0)
fruits.clear()
evens = [x for x in numbers if x % 2 == 0]
c.修改元素
fruits = ['apple', 'banana', 'orange']
fruits[1] = 'mango'
fruits[0:2] = ['peach', 'pear']
numbers = [1, 2, 3, 4, 5]
for i, num in enumerate(numbers):
if num % 2 == 0:
numbers[i] = num * 2
03.列表方法
a.排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
numbers.sort(reverse=True)
words = ['apple', 'banana', 'cherry', 'date']
words.sort(key=len)
words.sort(key=str.lower)
sorted_numbers = sorted(numbers)
b.反转
fruits = ['apple', 'banana', 'orange']
fruits.reverse()
reversed_fruits = fruits[::-1]
for fruit in reversed(fruits):
print(fruit)
c.统计
numbers = [1, 2, 2, 3, 2, 4, 2, 5]
count_twos = numbers.count(2)
from collections import Counter
counter = Counter(numbers)
length = len(numbers)
max_val = max(numbers)
min_val = min(numbers)
total = sum(numbers)
d.查找
fruits = ['apple', 'banana', 'orange', 'apple']
first_apple = fruits.index('apple')
second_apple = fruits.index('apple', 1)
has_orange = 'orange' in fruits
has_grape = 'grape' in fruits
def find_all(lst, target):
return [i for i, x in enumerate(lst) if x == target]
apple_positions = find_all(fruits, 'apple')
04.列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
result = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
matrix = [[i*j for j in range(3)] for i in range(3)]
words = ['hello', 'world', 'python']
uppercase = [word.upper() for word in words]
nested = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested for item in sublist]
05.代码示例
def list_operations_demo():
"""列表操作综合示例"""
print("=== 列表操作示例 ===")
# 创建列表
fruits = ['苹果', '香蕉', '橙子']
print(f"初始列表: {fruits}")
# 添加元素
fruits.append('葡萄')
fruits.insert(1, '芒果')
print(f"添加元素后: {fruits}")
# 访问和切片
print(f"第一个元素: {fruits[0]}")
print(f"切片 [1:3]: {fruits[1:3]}")
# 修改元素
fruits[0] = '桃子'
print(f"修改元素后: {fruits}")
# 删除元素
removed = fruits.pop()
print(f"删除 '{removed}' 后: {fruits}")
# 列表方法
print(f"列表长度: {len(fruits)}")
print(f"'香蕉' 出现次数: {fruits.count('香蕉')}")
# 排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"原数字列表: {numbers}")
numbers.sort()
print(f"排序后: {numbers}")
# 列表推导式
squares = [x**2 for x in range(1, 6)]
print(f"1-5的平方: {squares}")
# 过滤偶数
evens = [x for x in numbers if x % 2 == 0]
print(f"偶数: {evens}")
def nested_lists_demo():
"""嵌套列表示例"""
print("\n=== 嵌套列表示例 ===")
# 二维数组
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("3x3矩阵:")
for row in matrix:
print(row)
# 访问嵌套元素
print(f"中心元素: {matrix[1][1]}")
# 矩阵转置
transposed = [[row[i] for row in matrix] for i in range(3)]
print("转置矩阵:")
for row in transposed:
print(row)
if __name__ == "__main__":
list_operations_demo()
nested_lists_demo()
2.2 元组(Tuple)
00.总结
a.说明
元组是Python中不可变的有序序列容器,用于存储多个元素的集合。
一旦创建就不能修改,这使得元组在需要数据保护时非常有用。
元组可以包含任意类型的元素,支持索引和切片操作。
b.特点
不可变性,创建后无法修改元素内容;
有序性,元素按插入顺序存储;
异构性,可以包含不同类型的元素;
支持索引和切片,和列表一样的访问方式;
可以作为字典的键,因为不可变且可哈希;
内存效率,通常比列表占用更少内存。
c.与列表对比
元组不可变,列表可变;
元组创建速度更快,内存占用更少;
元组可以作为字典键,列表不能;
元组适用于不变的数据集合,列表适用于需要修改的数据;
元组使用小括号(),列表使用方括号[]。
01.元组创建和访问
a.创建元组
empty_tuple = ()
single_tuple = (1,)
numbers = (1, 2, 3, 4, 5)
mixed = (1, 'hello', 3.14, True)
auto_tuple = 1, 2, 3, 4, 5
from_string = tuple('hello')
from_list = tuple([1, 2, 3])
squares = tuple(x**2 for x in range(5))
b.访问元素
fruits = ('苹果', '香蕉', '橙子', '葡萄')
first = fruits[0]
last = fruits[-1]
second = fruits[1]
nested = ((1, 2), (3, 4), (5, 6))
element = nested[1][0]
point = (3, 4)
x, y = point
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
c.切片操作
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
first_three = numbers[0:3]
last_three = numbers[-3:]
middle = numbers[2:8]
every_second = numbers[::2]
reversed_tuple = numbers[::-1]
02.元组操作
a.拼接
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
result = (0,) + tuple1 + tuple2 + (7, 8)
b.重复
single = (1, 2)
repeated = single * 3
empty = ()
empty_repeated = empty * 5
c.成员测试
fruits = ('苹果', '香蕉', '橙子')
has_banana = '香蕉' in fruits
has_grape = '葡萄' in fruits
not_orange = '橙子' not in fruits
try:
index = fruits.index('橙子')
except ValueError:
index = -1
03.元组方法
# count():统计元素出现次数
numbers = (1, 2, 2, 3, 2, 4, 2, 5)
count_twos = numbers.count(2) # 4
# index():查找元素位置
fruits = ('苹果', '香蕉', '橙子', '苹果')
first_apple = fruits.index('苹果') # 0
second_apple = fruits.index('苹果', 1) # 3(从索引1开始搜索)
# 内置函数操作
length = len(numbers) # 8
maximum = max(numbers) # 5
minimum = min(numbers) # 1
total = sum(numbers) # 21
# 元素存在性检查
def safe_index(tpl, element, default=-1):
"""安全地获取元素索引"""
try:
return tpl.index(element)
except ValueError:
return default
04.命名元组(namedtuple)
from collections import namedtuple
# 创建命名元组类型
Point = namedtuple('Point', ['x', 'y'])
Color = namedtuple('Color', 'red green blue')
# 创建命名元组实例
p1 = Point(1, 2)
p2 = Point(x=3, y=4)
red = Color(255, 0, 0)
# 访问属性
print(f"点p1的坐标: ({p1.x}, {p1.y})") # (1, 2)
# 可以像普通元组一样使用
x, y = p1
print(f"解包: x={x}, y={y}")
# _replace()方法创建新实例
p3 = p1._replace(x=10) # Point(x=10, y=2)
# _asdict()方法转为字典
point_dict = p2._asdict() # {'x': 3, 'y': 4}
# _fields属性查看字段名
fields = Point._fields # ('x', 'y')
05.代码示例
def tuple_operations_demo():
"""元组操作综合示例"""
print("=== 元组操作示例 ===")
# 创建元组
fruits = ('苹果', '香蕉', '橙子')
print(f"水果元组: {fruits}")
# 访问元素
print(f"第一个水果: {fruits[0]}")
print(f"最后水果: {fruits[-1]}")
# 元组解包
a, b, c = fruits
print(f"解包后: a={a}, b={b}, c={c}")
# 拼接和重复
numbers = (1, 2, 3)
combined = numbers + numbers * 2
print(f"拼接重复: {combined}")
# 成员测试
print(f"'香蕉' 在元组中: {'香蕉' in fruits}")
print(f"'葡萄' 不在元组中: {'葡萄' not in fruits}")
# 元组方法
print(f"元组长度: {len(fruits)}")
print(f"元组中的最大值: {max(fruits)}") # 按字符串比较
def tuple_vs_list_demo():
"""元组与列表对比示例"""
print("\n=== 元组vs列表对比 ===")
# 性能测试
import time
# 创建测试
start_time = time.time()
for _ in range(100000):
lst = [1, 2, 3, 4, 5]
list_time = time.time() - start_time
start_time = time.time()
for _ in range(100000):
tpl = (1, 2, 3, 4, 5)
tuple_time = time.time() - start_time
print(f"列表创建时间: {list_time:.6f}秒")
print(f"元组创建时间: {tuple_time:.6f}秒")
# 作为字典键
dict_with_tuple = {(1, 2): "元组键"}
print(f"元组作为键: {dict_with_tuple}")
# 尝试使用列表作为键(会报错)
try:
dict_with_list = {[1, 2]: "列表键"}
except TypeError as e:
print(f"列表不能作为键: {e}")
def namedtuple_demo():
"""命名元组示例"""
from collections import namedtuple
print("\n=== 命名元组示例 ===")
# 定义点类型
Point = namedtuple('Point', ['x', 'y'])
# 创建点
p1 = Point(1, 2)
p2 = Point(x=3, y=4)
print(f"点p1: {p1}")
print(f"点p2: {p2}")
print(f"p1的x坐标: {p1.x}")
print(f"p2的y坐标: {p2.y}")
# 计算距离
distance = ((p2.x - p1.x)**2 + (p2.y - p1.y)**2)**0.5
print(f"两点距离: {distance:.2f}")
if __name__ == "__main__":
tuple_operations_demo()
tuple_vs_list_demo()
namedtuple_demo()
2.3 字符串(String)
00.总结
a.说明
字符串是Python中用于表示文本数据的不可变序列类型
字符串是Unicode字符的有序集合,支持各种文本操作和处理
Python提供了丰富的字符串方法和操作符用于文本处理
b.特点
不可变性:字符串创建后不能修改,修改操作会创建新字符串
有序性:字符按顺序存储,支持索引和切片访问
Unicode支持:原生支持多语言字符和表情符号
丰富的方法:提供大量内置方法用于文本处理
格式化支持:多种字符串格式化方式
正则表达式:与re模块结合支持复杂的模式匹配
c.字符串操作类
字符串操作可分为以下几类:
访问操作:索引、切片、遍历
查找操作:find、index、count、in运算符
判断操作:is系列方法、startwith、endwith
转换操作:大小写转换、字符类型判断
格式化操作:format、f-string、%
分割连接操作:split、join、partition
替换操作:replace、translate、expandtabs
01.字符串创建
a.单引号和双引号
# 使用单引号创建字符串
single_quotes = 'Hello, World!'
chinese = '你好,世界!'
# 使用双引号创建字符串
double_quotes = "Python编程"
mixed = "Hello, 世界!"
# 引号的嵌套使用
quote1 = "他说:'Python很有趣'"
quote2 = '她回复:"是的,确实如此!"'
# 转义字符
escape_chars = "换行符:\n 制表符:\t 引号:\" 反斜杠:\\"
b.三引号字符串
# 三引号用于多行字符串
multi_line = """这是一个
多行字符串
示例"""
# 三引号保留格式
poem = """床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。"""
# 三引号用于文档字符串
def greet(name):
"""
向指定的人问好
Args:
name (str): 要问好的人名
Returns:
str: 问好的消息
"""
return f"Hello, {name}!"
c.原始字符串
# 原始字符串不处理转义字符
raw_string = r"C:\Users\Admin\Documents"
regex_pattern = r"\d{3}-\d{4}" # 正则表达式模式
# 普通字符串vs原始字符串
normal_path = "C:\Users\nice" # \n被解释为换行符
raw_path = r"C:\Users\nice" # \n作为普通字符
# 原始字符串的应用场景
file_path = r"D:\项目\代码\script.py"
url_pattern = r"https?://[\w./]+"
d.格式化字符串
# 使用%格式化
name = "张三"
age = 25
old_format = "姓名:%s,年龄:%d岁" % (name, age)
# 使用str.format()方法
format_method = "姓名:{0},年龄:{1}岁".format(name, age)
format_named = "姓名:{name},年龄:{age}岁".format(name=name, age=age)
# 使用f-string(Python 3.6+)
f_string = f"姓名:{name},年龄:{age}岁"
f_expression = f"明年年龄:{age + 1}岁"
# 格式化选项
pi = 3.1415926
formatted_pi = f"圆周率:{pi:.2f}" # 保留两位小数
# 数字格式化
number = 1234567
formatted_number = f"数字:{number:,}" # 千位分隔符
02.字符串操作
a.访问和遍历
# 索引访问
text = "Python编程"
first_char = text[0] # 'P'
last_char = text[-1] # '程'
# 切片操作
substring = text[0:6] # 'Python'
chinese_part = text[6:] # '编程'
# 遍历字符串
for char in "Hello":
print(char)
# 带索引遍历
for i, char in enumerate("Python"):
print(f"位置{i}:{char}")
# 字符串长度
length = len(text) # 8
b.字符串拼接
# 使用+运算符
greeting = "Hello" + ", " + "World" # 'Hello, World'
# 使用join()方法(推荐)
words = ["Python", "编程", "很", "有趣"]
sentence = "".join(words) # 'Python编程很有趣'
# 使用%格式化
template = "%s%s%s" % ("Hello", ", ", "Python")
# 使用f-string
name = "Alice"
message = f"Hello, {name}!" # 'Hello, Alice!'
# 使用字符串乘法
repeated = "Ha" * 3 # 'HaHaHa'
c.字符串比较
# 相等性比较
str1 = "Python"
str2 = "Python"
str3 = "python"
is_equal = str1 == str2 # True
case_sensitive = str1 == str3 # False
case_insensitive = str1.lower() == str3.lower() # True
# 大小比较(按字典序)
alphabet = ["apple", "banana", "cherry"]
sorted_alphabet = sorted(alphabet) # ['apple', 'banana', 'cherry']
# 比较运算符
result = "apple" < "banana" # True
upper_vs_lower = "A" < "a" # True(大写字母ASCII码较小)
# 自定义比较
def compare_strings(str1, str2, ignore_case=False):
if ignore_case:
str1, str2 = str1.lower(), str2.lower()
if str1 < str2:
return -1
elif str1 > str2:
return 1
else:
return 0
03.字符串查找和判断
a.查找方法
# find()方法:返回首次出现的位置,不存在返回-1
text = "Python编程很有趣,Python很强大"
first_python = text.find("Python") # 0
second_python = text.find("Python", 1) # 9
not_found = text.find("Java") # -1
# index()方法:类似find,但不存在时抛出异常
try:
position = text.index("编程") # 6
except ValueError:
position = -1
# rfind()和rindex():从右边查找
last_python = text.rfind("Python") # 9
# count():统计出现次数
python_count = text.count("Python") # 2
char_count = text.count("n") # 2
b.判断方法
# startswith()和endswith()
filename = "document.txt"
is_text_file = filename.endswith(".txt") # True
starts_with_doc = filename.startswith("doc") # True
# isalpha():是否全为字母
print("Python".isalpha()) # True
print("Python3".isalpha()) # False
# isdigit():是否全为数字
print("12345".isdigit()) # True
print("12a45".isdigit()) # False
# isalnum():是否全为字母或数字
print("Python3".isalnum()) # True
print("Python-3".isalnum()) # False
# isspace():是否全为空白字符
print(" ".isspace()) # True
print(" a ".isspace()) # False
# 其他判断方法
text = "hello world"
is_lower = text.islower() # True
is_upper = text.isupper() # False
is_title = text.istitle() # False
04.字符串修改
a.大小写转换
# lower():转小写
text = "Python PROGRAMMING"
lower_text = text.lower() # 'python programming'
# upper():转大写
upper_text = text.upper() # 'PYTHON PROGRAMMING'
# title():标题格式(每个单词首字母大写)
title_text = text.title() # 'Python Programming'
# capitalize():首字母大写,其余小写
capitalized = text.capitalize() # 'Python programming'
# swapcase():大小写互换
swapped = text.swapcase() # 'pYTHON programming'
b.去除空白
# strip():去除两端空白
text = " Python Programming "
stripped = text.strip() # 'Python Programming'
# lstrip():去除左侧空白
left_stripped = text.lstrip() # 'Python Programming '
# rstrip():去除右侧空白
right_stripped = text.rstrip() # ' Python Programming'
# 去除指定字符
messy = "***Hello World***"
clean = messy.strip("*") # 'Hello World'
# 去除多个字符
text2 = "xyxHello Worldyxy"
clean2 = text2.strip("xy") # 'Hello World'
c.替换
# replace():替换子串
text = "Python is great, Python is powerful"
replaced = text.replace("Python", "Java") # 'Java is great, Java is powerful'
# 限制替换次数
limited = text.replace("Python", "Java", 1) # 'Java is great, Python is powerful'
# 批量替换
def multiple_replace(text, replacements):
result = text
for old, new in replacements.items():
result = result.replace(old, new)
return result
replacements = {"Python": "Java", "great": "awesome"}
batch_replaced = multiple_replace(text, replacements)
d.分割
# split():按指定分隔符分割
text = "Python,Java,C++,JavaScript"
languages = text.split(",") # ['Python', 'Java', 'C++', 'JavaScript']
# 分割次数限制
limited_split = text.split(",", 2) # ['Python', 'Java', 'C++,JavaScript']
# splitlines():按行分割
multi_line = "第一行\n第二行\n第三行"
lines = multi_line.splitlines() # ['第一行', '第二行', '第三行']
# partition():分割成三部分(分隔符前、分隔符、分隔符后)
text = "user@example.com"
username, sep, domain = text.partition("@") # 'user', '@', 'example.com'
e.连接
# join():连接字符串列表
words = ["Python", "编程", "很", "有趣"]
sentence = "".join(words) # 'Python编程很有趣'
spaced = " ".join(words) # 'Python 编程 很 有趣'
# 连接数字(需要转换)
numbers = [1, 2, 3, 4, 5]
number_string = "-".join(str(n) for n in numbers) # '1-2-3-4-5'
# 使用不同分隔符
comma_separated = ",".join(words) # 'Python,编程,很,有趣'
line_separated = "\n".join(words) # 每个词占一行
05.字符串格式化
a.% 格式化
# 基本格式化
name = "张三"
age = 25
height = 1.75
old_style = "姓名:%s,年龄:%d岁,身高:%.2f米" % (name, age, height)
# 格式化说明符
# %s:字符串
# %d:整数
# %f:浮点数
# %.2f:保留两位小数的浮点数
# %x:十六进制
# %o:八进制
# 字典格式化
data = {"name": "李四", "age": 30}
dict_format = "姓名:%(name)s,年龄:%(age)d岁" % data
b.format() 方法
# 位置参数
text = "Hello {}, you are {} years old".format("Alice", 25)
# 索引参数
text2 = "Hello {1}, you are {0} years old".format(25, "Alice")
# 关键字参数
text3 = "Hello {name}, you are {age} years old".format(
name="Bob", age=30)
# 格式化选项
pi = 3.1415926
formatted = "Pi = {:.2f}".format(pi) # 保留两位小数
# 对齐和填充
aligned = "{:<10}|{:^10}|{:>10}".format(
"左对齐", "居中", "右对齐")
# 数字格式化
number = 1234567
with_separator = "{:,}".format(number) # '1,234,567'
c.f-string
# 基本f-string
name = "Charlie"
age = 35
f_text = f"Hello {name}, you are {age} years old"
# 表达式计算
x, y = 10, 20
calculation = f"{x} + {y} = {x + y}"
# 格式化选项
pi = 3.1415926
f_formatted = f"Pi = {pi:.2f}"
# 调用方法
text = "hello world"
f_method = f"Upper: {text.upper()}, Length: {len(text)}"
# 字典和对象访问
person = {"name": "David", "age": 40}
f_dict = f"Name: {person['name']}, Age: {person['age']}"
# 多行f-string
multiline = f"""
姓名:{name}
年龄:{age}
信息:这是一个多行f-string示例
"""
06.代码示例
def string_operations_demo():
"""字符串操作综合示例"""
print("=== 字符串操作示例 ===")
# 字符串创建
name = "Python编程"
greeting = f"Hello, {name}!"
print(f"字符串: {name}")
print(f"问候语: {greeting}")
# 字符串方法
text = " Python Programming Language "
print(f"原字符串: '{text}'")
print(f"去除空白: '{text.strip()}'")
print(f"转大写: '{text.upper()}'")
print(f"转小写: '{text.lower()}'")
print(f"首字母大写: '{text.capitalize()}'")
# 字符串查找
sentence = "Python is powerful and easy to learn"
print(f"\n查找 'Python': {sentence.find('Python')}")
print(f"包含 'Java': {'Java' in sentence}")
# 字符串分割和连接
words = sentence.split()
print(f"分割后: {words}")
print(f"连接: '-'.join(words)}")
# 字符串替换
replaced = sentence.replace("Python", "Java")
print(f"替换后: {replaced}")
def string_formatting_demo():
"""字符串格式化示例"""
print("\n=== 字符串格式化示例 ===")
name = "张三"
age = 25
score = 95.5
# %格式化
old_style = "姓名:%s,年龄:%d岁,分数:%.1f分" % (name, age, score)
print(f"%格式化: {old_style}")
# str.format()
format_method = "姓名:{0},年龄:{1}岁,分数:{2:.1f}分".format(name, age, score)
print(f"format方法: {format_method}")
# f-string
f_string = f"姓名:{name},年龄:{age}岁,分数:{score:.1f}分"
print(f"f-string: {f_string}")
# 数字格式化
number = 1234567.89
print(f"千位分隔符: {number:,}")
print(f"保留两位小数: {number:.2f}")
print(f"科学计数法: {number:.2e}")
def text_processing_demo():
"""文本处理示例"""
print("\n=== 文本处理示例 ===")
# 文本清洗
messy_text = " Hello World! "
cleaned = " ".join(messy_text.split())
print(f"原文本: '{messy_text}'")
print(f"清洗后: '{cleaned}'")
# 文本统计
paragraph = "Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。"
char_count = len(paragraph)
word_count = len(paragraph.split())
print(f"\n段落: {paragraph}")
print(f"字符数: {char_count}")
print(f"单词数: {word_count}")
# 文本分析
text = "Python python PYTHON"
lower_text = text.lower()
python_count = lower_text.count("python")
print(f"\n文本: {text}")
print(f"'python'出现次数: {python_count}")
if __name__ == "__main__":
string_operations_demo()
string_formatting_demo()
text_processing_demo()
2.4 字典(Dictionary)
00.总结
a.说明
字典是Python中用于存储键值对的可变容器类型
字典中的每个元素都是键值对(key:value)的组合
字典是无序的(Python 3.7+保持插入顺序),通过键来访问值
b.特点
键值对结构:每个元素由键和值组成
键必须唯一且不可变:可以使用字符串、数字、元组作为键
值可以是任意类型:包括数字、字符串、列表、字典等
动态性:可以随时添加、删除、修改键值对
查找效率高:基于哈希表的O(1)查找复杂度
支持嵌套:字典可以包含其他字典
c.应用场景
配置管理:存储应用程序配置参数
数据映射:建立不同数据间的对应关系
缓存实现:键值对形式的缓存存储
JSON处理:与JSON格式天然对应
数据聚合:统计和分组数据
对象属性:动态存储对象属性信息
01.字典创建和访问
a.创建字典
# 使用花括号创建空字典
empty_dict = {}
# 创建包含键值对的字典
student = {
"name": "张三",
"age": 20,
"major": "计算机科学"
}
# 使用dict()构造函数
person = dict(name="李四", age=25, city="北京")
# 从列表创建字典
keys = ["name", "age", "city"]
values = ["王五", 30, "上海"]
info = dict(zip(keys, values))
# 嵌套字典
company = {
"name": "科技公司",
"employees": {
"开发部": 20,
"测试部": 10,
"市场部": 15
},
"location": {
"city": "深圳",
"address": "科技园"
}
}
# 使用字典推导式
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
b.访问元素
# 通过键访问值
student = {"name": "张三", "age": 20, "major": "计算机科学"}
name = student["name"] # "张三"
age = student["age"] # 20
# 使用get()方法(更安全)
major = student.get("major") # "计算机科学"
grade = student.get("grade", "大一") # "大一"(默认值)
# 访问嵌套字典
company = {
"name": "科技公司",
"location": {"city": "深圳", "address": "科技园"}
}
city = company["location"]["city"] # "深圳"
# 使用get()访问嵌套结构
address = company.get("location", {}).get("address", "未知") # "科技园"
c.修改元素
# 通过键修改值
student = {"name": "张三", "age": 20}
student["age"] = 21 # 修改年龄
# 使用update()方法批量更新
student.update({
"major": "计算机科学",
"grade": "大二",
"gpa": 3.8
})
# 修改嵌套字典
company = {
"name": "科技公司",
"info": {"employees": 50, "revenue": 1000000}
}
company["info"]["employees"] = 60 # 修改员工数
# 深度更新嵌套字典
def deep_update(original, updates):
for key, value in updates.items():
if key in original and isinstance(original[key], dict) and isinstance(value, dict):
deep_update(original[key], value)
else:
original[key] = value
updates = {
"info": {
"employees": 65,
"profit": 200000
}
}
deep_update(company, updates)
02.字典操作
a.添加和删除
# 添加新键值对
student = {"name": "张三", "age": 20}
student["major"] = "计算机科学" # 添加专业
student["gpa"] = 3.8 # 添加GPA
# 使用setdefault()添加(仅在键不存在时)
student.setdefault("grade", "大一") # 添加年级
student.setdefault("name", "李四") # 不修改,因为键已存在
# 删除键值对
del student["gpa"] # 删除GPA
# 使用pop()删除并返回值
removed_major = student.pop("major") # 删除并返回专业
print(f"删除的专业: {removed_major}")
# 使用pop()提供默认值
grade = student.pop("grade", "未知") # 安全删除
# 使用clear()清空字典
student.clear() # {}
# 删除字典
del student # 删除整个字典对象
b.遍历字典
student = {
"name": "张三",
"age": 20,
"major": "计算机科学",
"gpa": 3.8
}
# 遍历键
print("所有键:")
for key in student:
print(f" {key}")
# 遍历键(使用keys()方法)
print("\n使用keys()遍历:")
for key in student.keys():
print(f" {key}")
# 遍历值
print("\n所有值:")
for value in student.values():
print(f" {value}")
# 遍历键值对
print("\n键值对:")
for key, value in student.items():
print(f" {key}: {value}")
# 带索引遍历
print("\n带索引遍历:")
for index, (key, value) in enumerate(student.items()):
print(f" {index}. {key}: {value}")
c.字典方法
student = {
"name": "张三",
"age": 20,
"major": "计算机科学"
}
# 获取字典信息
keys = student.keys() # 返回键的视图
values = student.values() # 返回值的视图
items = student.items() # 返回键值对的视图
# 检查键是否存在
has_name = "name" in student # True
has_grade = "grade" in student # False
# 获取值(安全方式)
name = student.get("name", "未知") # "张三"
grade = student.get("grade", "未设置") # "未设置"
# 合并字典(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = dict1 | dict2 # {"a": 1, "b": 2, "c": 3, "d": 4}
# 复制字典
shallow_copy = student.copy() # 浅拷贝
# 深拷贝嵌套字典
import copy
nested_dict = {"info": {"name": "张三"}}
deep_copy = copy.deepcopy(nested_dict)
03.字典推导式
# 基本字典推导式
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 带条件的字典推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 字符串处理
text = "hello world"
char_count = {char: text.count(char) for char in set(text)}
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
# 列表转字典
students = ["张三", "李四", "王五"]
student_dict = {name: f"学生{name}" for name in students}
# {'张三': '学生张三', '李四': '学生李四', '王五': '学生王五'}
# 嵌套结构转换
data = [
{"name": "张三", "score": 90},
{"name": "李四", "score": 85},
{"name": "王五", "score": 95}
]
score_dict = {item["name"]: item["score"] for item in data}
# {'张三': 90, '李四': 85, '王五': 95}
04.有序字典(OrderedDict)
from collections import OrderedDict
# 创建有序字典(保持插入顺序)
od = OrderedDict()
od["first"] = 1
od["second"] = 2
od["third"] = 3
# 移动元素位置
od.move_to_end("first") # 移到末尾
od.move_to_end("second", last=False) # 移到开头
# 从有序字典的两端操作
first_item = od.popitem(last=False) # 弹出第一个元素
last_item = od.popitem() # 弹出最后一个元素
# 有序字典的相等性比较
od1 = OrderedDict([("a", 1), ("b", 2)])
od2 = OrderedDict([("b", 2), ("a", 1)])
print(od1 == od2) # False,顺序不同
# 普通字典(Python 3.7+也保持插入顺序)
regular_dict = {"a": 1, "b": 2, "c": 3}
05.默认字典(defaultdict)
from collections import defaultdict
# 使用list作为默认值
groups = defaultdict(list)
groups["students"].append("张三")
groups["students"].append("李四")
# 此时groups["students"] = ["张三", "李四"]
# 使用int作为默认值(用于计数)
counter = defaultdict(int)
words = ["apple", "banana", "apple", "orange", "banana"]
for word in words:
counter[word] += 1
# defaultdict(int, {'apple': 2, 'banana': 2, 'orange': 1})
# 使用set作为默认值(用于去重)
unique_items = defaultdict(set)
data = [
("group1", "item1"),
("group1", "item2"),
("group2", "item1"),
("group2", "item1") # 重复
]
for group, item in data:
unique_items[group].add(item)
# {'group1': {'item1', 'item2'}, 'group2': {'item1'}}
# 自定义默认值函数
def default_dict_factory():
return {"count": 0, "items": []}
stats = defaultdict(default_dict_factory)
stats["category1"]["count"] += 1
stats["category1"]["items"].append("item1")
06.代码示例
def dictionary_operations_demo():
"""字典操作综合示例"""
print("=== 字典操作示例 ===")
# 创建字典
student = {
"name": "张三",
"age": 20,
"major": "计算机科学",
"gpa": 3.8
}
print(f"学生信息: {student}")
# 访问元素
name = student.get("name", "未知")
age = student.get("age", 0)
print(f"姓名: {name}, 年龄: {age}")
# 修改元素
student["age"] = 21
student["gpa"] = 3.9
print(f"修改后: {student}")
# 添加元素
student["grade"] = "大二"
print(f"添加年级后: {student}")
# 删除元素
removed_gpa = student.pop("gpa")
print(f"删除的GPA: {removed_gpa}")
print(f"删除后: {student}")
# 遍历字典
print("\n学生详细信息:")
for key, value in student.items():
print(f" {key}: {value}")
def dictionary_methods_demo():
"""字典方法示例"""
print("\n=== 字典方法示例 ===")
student = {
"name": "李四",
"age": 22,
"major": "软件工程"
}
# 字典视图
keys_view = student.keys()
values_view = student.values()
items_view = student.items()
print(f"键视图: {list(keys_view)}")
print(f"值视图: {list(values_view)}")
print(f"键值对视图: {list(items_view)}")
# 检查键存在
print(f"\n包含'major': {'major' in student}")
print(f"包含'gpa': {'gpa' in student}")
# 安全访问
gpa = student.get("gpa", "未设置")
print(f"GPA: {gpa}")
# 批量更新
updates = {
"gpa": 3.7,
"grade": "大三",
"courses": ["数据结构", "算法", "数据库"]
}
student.update(updates)
print(f"\n批量更新后: {student}")
def nested_dictionary_demo():
"""嵌套字典示例"""
print("\n=== 嵌套字典示例 ===")
# 创建嵌套字典
university = {
"name": "科技大学",
"departments": {
"计算机学院": {
"students": 500,
"professors": 30,
"courses": ["Python", "Java", "数据结构"]
},
"数学学院": {
"students": 300,
"professors": 25,
"courses": ["高等数学", "线性代数", "概率论"]
}
},
"location": {
"city": "北京",
"address": "学院路1号"
}
}
# 访问嵌套数据
cs_students = university["departments"]["计算机学院"]["students"]
location = university["location"]["city"]
print(f"计算机学院学生数: {cs_students}")
print(f"大学位置: {location}")
# 修改嵌套数据
university["departments"]["计算机学院"]["students"] = 520
university["departments"]["计算机学院"]["courses"].append("机器学习")
print(f"\n更新后计算机学院: {university['departments']['计算机学院']}")
def dictionary_comprehension_demo():
"""字典推导式示例"""
print("\n=== 字典推导式示例 ===")
# 基本推导式
squares = {x: x**2 for x in range(1, 6)}
print(f"平方字典: {squares}")
# 条件推导式
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(f"偶数平方: {even_squares}")
# 字符串处理
sentence = "hello world python"
char_freq = {char: sentence.count(char) for char in set(sentence)}
print(f"字符频率: {char_freq}")
# 数据转换
students = ["张三", "李四", "王五"]
scores = [90, 85, 95]
student_scores = {name: score for name, score in zip(students, scores)}
print(f"学生成绩: {student_scores}")
if __name__ == "__main__":
dictionary_operations_demo()
dictionary_methods_demo()
nested_dictionary_demo()
dictionary_comprehension_demo()
2.5 集合(Set)
00.总结
a.说明
集合是Python中用于存储唯一元素的无序容器类型
集合中的元素不能重复,且必须是可哈希的(不可变类型)
集合主要用于去重、成员测试和数学集合运算
b.特点
唯一性:集合中不会出现重复元素
无序性:元素没有固定顺序,不能通过索引访问
可变性:普通集合可以添加和删除元素
高效查找:基于哈希表的O(1)查找复杂度
支持数学运算:并集、交集、差集、对称差集等
c.应用场景
数据去重:从列表或其他序列中移除重复元素
快速成员测试:检查元素是否存在于集合中
数学集合运算:处理集合间的各种运算关系
数据筛选:根据条件过滤数据
关系处理:处理两个或多个数据集之间的关系
01.集合创建和操作
a.创建集合
# 使用花括号创建集合(空集合必须用set())
empty_set = set()
# 从元素创建集合
numbers = {1, 2, 3, 4, 5}
fruits = {"苹果", "香蕉", "橙子"}
# 从其他容器创建集合
list_to_set = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}(自动去重)
string_to_set = set("hello") # {'h', 'e', 'l', 'o'}(去重)
# 使用集合推导式
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
even_numbers = {x for x in range(10) if x % 2 == 0} # {0, 2, 4, 6, 8}
# 注意:不能创建包含可变元素的集合
# invalid = {[1, 2], [3, 4]} # TypeError,列表不可哈希
valid = {(1, 2), (3, 4)} # 可以,元组可哈希
b.添加和删除元素
# 添加元素
numbers = {1, 2, 3}
numbers.add(4) # {1, 2, 3, 4}
# 添加重复元素(不会生效)
numbers.add(3) # 仍然 {1, 2, 3, 4}
# 添加多个元素
numbers.update({5, 6, 7}) # {1, 2, 3, 4, 5, 6, 7}
numbers.update([8, 9, 10]) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
# 删除元素
numbers.remove(5) # 删除5,如果不存在会抛出KeyError
# 安全删除
numbers.discard(100) # 删除100,不存在也不会报错
# 随机删除并返回元素
popped = numbers.pop() # 删除并返回一个元素(因为是无序的)
# 清空集合
numbers.clear() # set()
c.集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 并集(union)
union_set = set1 | set2 # {1, 2, 3, 4, 5, 6}
union_method = set1.union(set2) # 同上
# 交集(intersection)
intersection_set = set1 & set2 # {3, 4}
intersection_method = set1.intersection(set2) # 同上
# 差集(difference)
difference_set = set1 - set2 # {1, 2}(在set1但不在set2中)
difference_method = set1.difference(set2) # 同上
# 对称差集(symmetric difference)
sym_diff = set1 ^ set2 # {1, 2, 5, 6}(在其中一个集合中但不同时在两个集合中)
sym_diff_method = set1.symmetric_difference(set2) # 同上
02.集合方法
a.并集操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
# 多个集合的并集
multi_union = set1 | set2 | set3 # {1, 2, 3, 4, 5, 6, 7}
# update():原地并集操作
set1.update(set2) # set1变为 {1, 2, 3, 4, 5}
set1.update(set3) # set1变为 {1, 2, 3, 4, 5, 6, 7}
# union():返回新的并集
new_set = set1.union(set2, set3)
b.交集操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set3 = {4, 5, 7, 8}
# 多个集合的交集
multi_intersection = set1 & set2 & set3 # {4}
# intersection():返回新的交集
new_intersection = set1.intersection(set2, set3)
# intersection_update():原地交集操作
set1.intersection_update(set2) # set1变为 {3, 4}
c.差集操作
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set3 = {5, 6, 8, 9}
# 连续差集
consecutive_diff = set1 - set2 - set3 # {1, 2, 3}
# difference():返回新的差集
new_diff = set1.difference(set2, set3)
# difference_update():原地差集操作
set1.difference_update(set2) # set1变为 {1, 2, 3}
d.对称差集操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# symmetric_difference():返回新的对称差集
new_sym_diff = set1.symmetric_difference(set2) # {1, 2, 5, 6}
# symmetric_difference_update():原地对称差集操作
set1.symmetric_difference_update(set2) # set1变为 {1, 2, 5, 6}
03.冻结集合(frozenset)
# 创建冻结集合
frozen1 = frozenset([1, 2, 3, 4])
frozen2 = frozenset("hello") # frozenset({'h', 'e', 'l', 'o'})
# 冻结集合不可修改
# frozen1.add(5) # TypeError,不支持添加
# frozen1.remove(1) # TypeError,不支持删除
# 冻结集合可以作为字典的键
cache = {
frozenset([1, 2, 3]): "第一组",
frozenset([4, 5, 6]): "第二组"
}
# 冻结集合支持集合运算
set1 = frozenset([1, 2, 3, 4])
set2 = frozenset([3, 4, 5, 6])
union = set1 | set2 # frozenset({1, 2, 3, 4, 5, 6})
intersection = set1 & set2 # frozenset({3, 4})
# 冻结集合的应用场景
def memoize(func):
"""简单的记忆化装饰器"""
cache = {}
def wrapper(*args):
# 使用frozenset作为参数的哈希键
frozen_args = frozenset(args)
if frozen_args not in cache:
cache[frozen_args] = func(*args)
return cache[frozen_args]
return wrapper
04.集合推导式
# 基本集合推导式
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
# 带条件的集合推导式
even_squares = {x**2 for x in range(10) if x % 2 == 0}
# {0, 4, 16, 36, 64}
# 字符串处理
text = "hello world"
unique_chars = {char.upper() for char in text if char.isalpha()}
# {'H', 'E', 'L', 'O', 'W', 'R', 'D'}
# 复杂条件
numbers = range(1, 21)
special_numbers = {
x for x in numbers
if x % 2 == 0 and x % 3 == 0
} # {6, 12, 18}(能被2和3整除的数)
# 多重条件
data = range(1, 51)
filtered_set = {
x for x in data
if x % 2 == 0 and x > 10 and x < 40
} # 10到40之间的偶数
# 集合推导式与函数调用结合
import math
prime_squares = {
x**2 for x in range(2, 20)
if all(x % i != 0 for i in range(2, int(math.sqrt(x)) + 1))
} # 质数的平方
05.代码示例
def set_operations_demo():
"""集合操作综合示例"""
print("=== 集合操作示例 ===")
# 创建集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(f"集合1: {set1}")
print(f"集合2: {set2}")
# 集合运算
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
sym_diff_set = set1 ^ set2
print(f"\n并集: {union_set}")
print(f"交集: {intersection_set}")
print(f"差集 (set1 - set2): {difference_set}")
print(f"对称差集: {sym_diff_set}")
# 集合方法
print(f"\n集合1的长度: {len(set1)}")
print(f"6 是否在集合2中: {6 in set2}")
print(f"3 是否不在集合2中: {3 not in set2}")
def set_methods_demo():
"""集合方法示例"""
print("\n=== 集合方法示例 ===")
# 创建集合并操作
numbers = {1, 2, 3}
print(f"初始集合: {numbers}")
# 添加元素
numbers.add(4)
numbers.update({5, 6, 7})
print(f"添加后: {numbers}")
# 删除操作
numbers.discard(7) # 安全删除
print(f"删除7后: {numbers}")
removed = numbers.pop() # 随机删除
print(f"随机删除的元素: {removed}")
print(f"删除后: {numbers}")
# 集合关系
set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
set_c = {4, 5, 6}
print(f"\n{set_a} 是 {set_b} 的子集: {set_a.issubset(set_b)}")
print(f"{set_b} 是 {set_a} 的超集: {set_b.issuperset(set_a)}")
print(f"{set_a} 和 {set_c} 是否不相交: {set_a.isdisjoint(set_c)}")
def set_comprehension_demo():
"""集合推导式示例"""
print("\n=== 集合推导式示例 ===")
# 基本推导式
squares = {x**2 for x in range(1, 6)}
print(f"1-5的平方: {squares}")
# 条件推导式
even_squares = {x**2 for x in range(1, 11) if x % 2 == 0}
print(f"偶数的平方: {even_squares}")
# 字符串处理
text = "hello world python programming"
unique_chars = {char.upper() for char in text if char.isalpha()}
print(f"字符串中的唯一字母: {sorted(unique_chars)}")
# 质数筛选
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
primes = {x for x in range(2, 50) if is_prime(x)}
print(f"2-49中的质数: {sorted(primes)}")
def practical_set_demo():
"""集合实际应用示例"""
print("\n=== 集合实际应用 ===")
# 数据去重
data = [1, 2, 2, 3, 4, 3, 5, 1, 6, 4, 7]
unique_data = set(data)
print(f"原数据: {data}")
print(f"去重后: {list(unique_data)}")
# 找出两个列表的共同元素
list1 = ["苹果", "香蕉", "橙子", "葡萄"]
list2 = ["橙子", "葡萄", "西瓜", "芒果"]
common_fruits = set(list1) & set(list2)
print(f"\n列表1: {list1}")
print(f"列表2: {list2}")
print(f"共同水果: {list(common_fruits)}")
# 找出只在其中一个列表中的元素
unique_to_list1 = set(list1) - set(list2)
unique_to_list2 = set(list2) - set(list1)
unique_either = set(list1) ^ set(list2)
print(f"只在列表1中: {list(unique_to_list1)}")
print(f"只在列表2中: {list(unique_to_list2)}")
print(f"在其中一个列表中: {list(unique_either)}")
if __name__ == "__main__":
set_operations_demo()
set_methods_demo()
set_comprehension_demo()
practical_set_demo()
2.6 容器通用操作
00.总结
a.迭代器
迭代器是Python中实现迭代协议的对象,支持逐个访问容器元素
迭代器提供了一种统一的访问序列的方式,无论底层容器类型如何
迭代器遵循惰性求值原则,只在需要时计算下一个值
b.生成器
生成器是一种特殊的迭代器,使用函数语法创建
生成器允许使用yield关键字暂停函数执行并保存状态
生成器在处理大数据集时非常有用,因为它们不会一次性加载所有数据到内存
01.迭代器(Iterator)
a.iter() 和 next()
# 获取迭代器
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
# 使用next()获取元素
first = next(iterator) # 1
second = next(iterator) # 2
third = next(iterator) # 3
# 使用for循环遍历迭代器
for item in iterator:
print(item) # 4, 5
# 迭代器耗尽后继续next()会抛出StopIteration
try:
next(iterator)
except StopIteration:
print("迭代器已耗尽")
# 字符串迭代器
text = "Hello"
text_iterator = iter(text)
for char in text_iterator:
print(char)
# 字典迭代器(默认遍历键)
student = {"name": "张三", "age": 20}
for key in iter(student):
print(f"键: {key}")
# 显式获取键、值、键值对的迭代器
for key in student.keys():
print(f"键: {key}")
for value in student.values():
print(f"值: {value}")
for key, value in student.items():
print(f"键值对: {key}: {value}")
b.自定义迭代器
class Countdown:
"""倒计时迭代器"""
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# 使用自定义迭代器
countdown = Countdown(5)
for num in countdown:
print(num) # 5, 4, 3, 2, 1
class Fibonacci:
"""斐波那契数列迭代器"""
def __init__(self, max_count):
self.max_count = max_count
self.count = 0
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.count >= self.max_count:
raise StopIteration
result = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return result
# 使用斐波那契迭代器
fib = Fibonacci(10)
print("斐波那契数列:")
for num in fib:
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
02.生成器(Generator)
a.生成器函数
def simple_generator():
"""简单生成器函数"""
yield 1
yield 2
yield 3
# 使用生成器函数
gen = simple_generator()
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
# 计数器生成器
def counter(start, end):
"""计数器生成器"""
current = start
while current <= end:
yield current
current += 1
# 使用计数器
for num in counter(1, 5):
print(num) # 1, 2, 3, 4, 5
# 斐波那契数列生成器
def fibonacci_generator(n):
"""生成前n个斐波那契数"""
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
# 使用斐波那契生成器
fib_gen = fibonacci_generator(10)
fib_sequence = list(fib_gen)
print(f"斐波那契数列: {fib_sequence}")
b.生成器表达式
# 基本生成器表达式
squares_gen = (x**2 for x in range(10))
# 使用生成器表达式
for square in squares_gen:
print(square) # 0, 1, 4, 9, 16, 25, 36, 49, 64, 81
# 条件生成器表达式
even_squares = (x**2 for x in range(10) if x % 2 == 0)
# 将生成器转换为列表(注意:这会消耗所有元素)
even_squares_list = list(even_squares)
print(f"偶数平方: {even_squares_list}")
# 复杂生成器表达式
import math
prime_squares = (
x**2 for x in range(2, 50)
if all(x % i != 0 for i in range(2, int(math.sqrt(x)) + 1))
)
# 逐个处理生成器元素
print("质数的平方:")
for prime_square in prime_squares:
print(prime_square, end=" ")
c.yield 关键字
def file_reader(filename):
"""逐行读取文件的生成器"""
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
yield line.strip()
# 使用文件读取生成器
# for line in file_reader('example.txt'):
# print(line)
def data_processor(data_stream):
"""数据处理管道"""
for item in data_stream:
# 数据预处理
processed = item.upper()
yield processed
# 使用数据处理生成器
words = ["hello", "world", "python"]
processor = data_processor(words)
for processed_word in processor:
print(processed_word) # HELLO, WORLD, PYTHON
def yield_from_example():
"""使用yield from的生成器"""
yield from range(3) # 0, 1, 2
yield from "ABC" # A, B, C
yield from [10, 20, 30] # 10, 20, 30
# 使用yield from
for item in yield_from_example():
print(item, end=" ") # 0 1 2 A B C 10 20 30
03.内置函数
a.len()、max()、min()
# len():获取容器长度
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3)
string_data = "hello"
set_data = {1, 2, 3}
dict_data = {"a": 1, "b": 2}
print(f"列表长度: {len(list_data)}") # 5
print(f"元组长度: {len(tuple_data)}") # 3
print(f"字符串长度: {len(string_data)}") # 5
print(f"集合长度: {len(set_data)}") # 3
print(f"字典长度: {len(dict_data)}") # 2
# max():获取最大值
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_num = max(numbers) # 9
max_char = max("hello") # 'o'(按字母顺序)
max_key = max(dict_data) # 'b'(字典键的最大值)
# 自定义比较规则
words = ["apple", "banana", "cherry"]
longest_word = max(words, key=len) # 'banana'(最长的词)
# min():获取最小值
min_num = min(numbers) # 1
shortest_word = min(words, key=len) # 'apple'(最短的词)
b.sum()、all()、any()
# sum():求和(仅对数值容器)
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # 15
sum_with_start = sum(numbers, 10) # 25(从10开始加)
# all():检查所有元素是否为真
bool_list1 = [True, True, True]
bool_list2 = [True, False, True]
numbers_pos = [1, 2, 3, 4] # 所有正数都为真
numbers_with_zero = [1, 2, 0, 4] # 0为假
print(f"all([True, True, True]): {all(bool_list1)}") # True
print(f"all([True, False, True]): {all(bool_list2)}") # False
print(f"all([1, 2, 3, 4]): {all(numbers_pos)}") # True
print(f"all([1, 2, 0, 4]): {all(numbers_with_zero)}") # False
# any():检查是否有元素为真
print(f"any([True, False, False]): {any([True, False, False])}") # True
print(f"any([False, False, False]): {any([False, False, False])}") # False
# 实际应用
def check_all_positive(numbers):
return all(num > 0 for num in numbers)
def has_even_number(numbers):
return any(num % 2 == 0 for num in numbers)
c.map()、filter()、reduce()
# map():对容器中每个元素应用函数
numbers = [1, 2, 3, 4, 5]
# 使用map将每个数字平方
squares = map(lambda x: x**2, numbers)
print(f"平方: {list(squares)}") # [1, 4, 9, 16, 25]
# 使用map处理字符串
words = ["hello", "world", "python"]
upper_words = map(str.upper, words)
print(f"大写: {list(upper_words)}") # ['HELLO', 'WORLD', 'PYTHON']
# 多容器map
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_pairs = map(lambda x, y: x + y, list1, list2)
print(f"配对求和: {list(sum_pairs)}") # [5, 7, 9]
# filter():过滤容器元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 过滤偶数
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(f"偶数: {list(even_numbers)}") # [2, 4, 6, 8, 10]
# 过滤长度大于3的单词
words = ["hi", "hello", "world", "a", "python"]
long_words = filter(lambda word: len(word) > 3, words)
print(f"长单词: {list(long_words)}") # ['hello', 'world', 'python']
# reduce():累积操作(需要从functools导入)
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# 求和
total = reduce(lambda x, y: x + y, numbers)
print(f"求和: {total}") # 15
# 求最大值
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(f"最大值: {maximum}") # 5
# 字符串连接
words = ["hello", " ", "world", "!"]
sentence = reduce(lambda x, y: x + y, words)
print(f"句子: {sentence}") # "hello world!"
d.zip()、enumerate()
# zip():将多个容器按索引配对
names = ["张三", "李四", "王五"]
ages = [20, 25, 30]
cities = ["北京", "上海", "广州"]
# 配对三个列表
combined = zip(names, ages, cities)
for name, age, city in combined:
print(f"{name}今年{age}岁,来自{city}")
# zip长度不一致时以最短的为准
short_list = [1, 2]
long_list = [10, 20, 30, 40]
zipped = zip(short_list, long_list)
print(f"不等长zip: {list(zipped)}") # [(1, 10), (2, 20)]
# 使用zip创建字典
keys = ["name", "age", "city"]
values = ["张三", 25, "北京"]
person_dict = dict(zip(keys, values))
print(f"字典: {person_dict}")
# enumerate():为容器元素添加索引
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
# 基本enumerate
for index, fruit in enumerate(fruits):
print(f"索引{index}: {fruit}")
# 指定起始索引
for i, fruit in enumerate(fruits, start=1):
print(f"第{i}个水果: {fruit}")
# enumerate与zip结合
for i, (name, score) in enumerate(zip(names, ages)):
print(f"第{i+1}名: {name},分数: {score}")
# 创建带索引的列表
indexed_list = list(enumerate(fruits))
print(f"带索引列表: {indexed_list}")
04.代码示例
def iterator_demo():
"""迭代器示例"""
print("=== 迭代器示例 ===")
# 基本迭代器使用
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
print("使用next()逐个获取元素:")
try:
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
print(next(iterator)) # 4
print(next(iterator)) # 5
# print(next(iterator)) # 会抛出StopIteration
except StopIteration:
print("迭代器已耗尽")
# 字符串迭代器
text = "Python"
text_iterator = iter(text)
print(f"\n字符串迭代器: {list(text_iterator)}")
# 字典迭代器
student = {"name": "张三", "age": 20, "major": "计算机科学"}
print(f"\n字典键迭代器: {list(iter(student))}")
print(f"字典值迭代器: {list(student.values())}")
print(f"字典项迭代器: {list(student.items())}")
def custom_iterator_demo():
"""自定义迭代器示例"""
print("\n=== 自定义迭代器示例 ===")
# 倒计时迭代器
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print("倒计时:")
countdown = Countdown(5)
for num in countdown:
print(num, end=" ") # 5 4 3 2 1
# 斐波那契迭代器
class Fibonacci:
def __init__(self, max_count):
self.max_count = max_count
self.count = 0
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.count >= self.max_count:
raise StopIteration
result = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return result
print("\n\n斐波那契数列:")
fib = Fibonacci(10)
fib_list = list(fib)
print(fib_list)
def generator_demo():
"""生成器示例"""
print("\n=== 生成器示例 ===")
# 生成器函数
def simple_counter(n):
for i in range(n):
yield i
print("简单计数器:")
counter = simple_counter(5)
for num in counter:
print(num, end=" ") # 0 1 2 3 4
# 斐波那契生成器
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
print("\n\n斐波那契生成器:")
fib_gen = fibonacci_generator(10)
fib_numbers = list(fib_gen)
print(fib_numbers)
# 生成器表达式
print("\n生成器表达式:")
squares_gen = (x**2 for x in range(10))
squares = list(squares_gen)
print(f"平方数: {squares}")
# 条件生成器表达式
even_squares = (x**2 for x in range(10) if x % 2 == 0)
print(f"偶数平方: {list(even_squares)}")
def builtin_functions_demo():
"""内置函数示例"""
print("\n=== 内置函数示例 ===")
# len(), max(), min()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"数字列表: {numbers}")
print(f"长度: {len(numbers)}")
print(f"最大值: {max(numbers)}")
print(f"最小值: {min(numbers)}")
# sum(), all(), any()
print(f"\n求和: {sum(numbers)}")
print(f"所有数字都大于0: {all(x > 0 for x in numbers)}")
print(f"是否有偶数: {any(x % 2 == 0 for x in numbers)}")
# map()示例
print(f"\nmap()示例:")
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(f"平方: {squares}")
words = ["hello", "world", "python"]
uppercase = list(map(str.upper, words))
print(f"大写: {uppercase}")
# filter()示例
print(f"\nfilter()示例:")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶数: {even_numbers}")
long_words = list(filter(lambda w: len(w) > 3, words))
print(f"长单词: {long_words}")
# reduce()示例
from functools import reduce
print(f"\nreduce()示例:")
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(f"乘积: {product}")
# zip()示例
print(f"\nzip()示例:")
names = ["张三", "李四", "王五"]
ages = [20, 25, 30]
cities = ["北京", "上海", "广州"]
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age}岁, 来自{city}")
# enumerate()示例
print(f"\nenumerate()示例:")
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
for index, fruit in enumerate(fruits, start=1):
print(f"第{index}个: {fruit}")
def advanced_container_operations():
"""高级容器操作示例"""
print("\n=== 高级容器操作 ===")
# 列表推导式 vs map()
numbers = range(1, 11)
# 使用map()
map_result = list(map(lambda x: x**2, numbers))
# 使用列表推导式
comprehension_result = [x**2 for x in numbers]
print(f"使用map: {map_result}")
print(f"使用推导式: {comprehension_result}")
# 嵌套操作
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(f"\n矩阵扁平化: {flattened}")
# 条件过滤
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"偶数的平方: {even_squares}")
# 字典推导式
words = ["hello", "world", "python"]
word_lengths = {word: len(word) for word in words}
print(f"单词长度字典: {word_lengths}")
# 集合推导式
numbers = [1, 2, 2, 3, 4, 3, 5, 1]
unique_squares = {x**2 for x in numbers}
print(f"唯一数的平方集合: {unique_squares}")
if __name__ == "__main__":
iterator_demo()
custom_iterator_demo()
generator_demo()
builtin_functions_demo()
advanced_container_operations()
3 函数
3.1 函数定义
00.总结
a.说明
函数是Python中用于封装可重用代码的基本单元,可以通过函数名调用执行特定任务。
函数提高了代码的模块化程度和可维护性。
b.函数组成
函数名、参数列表、函数体、返回值、文档字符串。
01.函数定义和调用
a.基本语法
def function_name():
print("Hello, World!")
def greet(name):
return f"Hello, {name}!"
function_name()
result = greet("Alice")
b.参数传递
def add(a, b):
return a + b
def multiply(x, y, z):
return x * y * z
result = add(3, 5)
product = multiply(2, 3, 4)
c.返回值
def get_max(a, b):
return a if a > b else b
def calculate_stats(numbers):
return sum(numbers), max(numbers), min(numbers)
total, maximum, minimum = calculate_stats([1, 2, 3, 4, 5])
02.参数类型
a.位置参数
def subtract(a, b):
return a - b
result = subtract(10, 3)
b.默认参数
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
message1 = greet("Alice")
message2 = greet("Bob", "Hi")
c.可变参数(*args)
def sum_all(*args):
return sum(args)
total = sum_all(1, 2, 3, 4, 5)
def create_person(name, age, *hobbies):
return {"name": name, "age": age, "hobbies": hobbies}
person = create_person("张三", 25, "阅读", "游泳", "编程")
d.关键字参数(**kwargs)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="张三", age=25, city="北京")
def process_data(data, **options):
verbose = options.get("verbose", False)
max_items = options.get("max_items", 100)
03.函数作用域
a.局部变量
def local_example():
x = 10
print(f"局部变量x: {x}")
local_example()
b.全局变量
global_var = 100
def global_example():
global global_var
global_var = 200
print(f"修改后的全局变量: {global_var}")
global_example()
print(f"全局变量值: {global_var}")
c.nonlocal 关键字
def outer():
x = 10
def inner():
nonlocal x
x = 20
print(f"内部函数中的x: {x}")
inner()
print(f"外部函数中的x: {x}")
outer()
3.2 Lambda 函数
00.总结
a.说明
Lambda函数是Python中的匿名函数,用于创建简单的、单行的函数。
通常用于需要函数对象但又不想正式定义函数的场合。
b.特点
匿名性、单行表达式、简洁语法、常用于函数式编程。
01.Lambda 表达式
a.基本语法
add = lambda x, y: x + y
square = lambda x: x ** 2
is_even = lambda x: x % 2 == 0
result = add(3, 5) # 8
squared = square(4) # 16
check = is_even(7) # False
b.使用场景
# 作为参数传递
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# 排序时使用
students = [("张三", 85), ("李四", 92), ("王五", 78)]
students.sort(key=lambda x: x[1])
# 条件表达式
get_grade = lambda score: "优秀" if score >= 90 else "良好" if score >= 80 else "及格"
02.高阶函数
a.map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
doubled = list(map(lambda x: x*2, numbers))
words = ["hello", "world", "python"]
uppercase = list(map(lambda word: word.upper(), words))
b.filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
greater_than_five = list(filter(lambda x: x > 5, numbers))
words = ["apple", "banana", "cherry", "date"]
long_words = list(filter(lambda word: len(word) > 5, words))
c.sorted()
students = [("张三", 85), ("李四", 92), ("王五", 78)]
by_score = sorted(students, key=lambda x: x[1])
by_name = sorted(students, key=lambda x: x[0])
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_desc = sorted(numbers, key=lambda x: -x)
3.3 装饰器
00.总结
a.说明
装饰器是Python中用于修改或扩展函数功能的强大工具,它允许在不修改原函数代码的情况下增加额外的功能。
b.应用场景
日志记录、性能监控、权限验证、缓存、事务处理等。
01.函数装饰器
a.基本装饰器
def my_decorator(func):
def wrapper():
print("函数执行前的操作")
func()
print("函数执行后的操作")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
b.带参数的装饰器
def timer_decorator(prefix):
def decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{prefix}: 执行时间 {end-start:.4f}秒")
return result
return wrapper
return decorator
@timer_decorator("计算时间")
def calculate():
total = sum(range(1000))
return total
calculate()
c.多个装饰器
def decorator1(func):
def wrapper():
print("装饰器1 - 前")
func()
print("装饰器1 - 后")
return wrapper
def decorator2(func):
def wrapper():
print("装饰器2 - 前")
func()
print("装饰器2 - 后")
return wrapper
@decorator1
@decorator2
def test():
print("原函数")
test()
02.类装饰器
class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print(f"调用次数: {self.count}")
return self.func(*args, **kwargs)
@CountCalls
def greet():
print("Hello!")
greet()
greet()
03.内置装饰器
a.@staticmethod
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
result = MathUtils.add(3, 5)
b.@classmethod
class Person:
def __init__(self, name):
self.name = name
@classmethod
def create_adult(cls, name):
return cls(name)
adult = Person.create_adult("张三")
c.@property
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
@property
def perimeter(self):
return 2 * (self.width + self.height)
rect = Rectangle(5, 3)
print(f"面积: {rect.area}")
print(f"周长: {rect.perimeter}")
04.functools 模块
a.@wraps
from functools import wraps
def log_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"调用函数: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_decorator
def add(a, b):
"""加法函数"""
return a + b
print(add.__name__) # add
print(add.__doc__) # 加法函数
b.@lru_cache
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 第一次调用会计算
result1 = fibonacci(10)
# 第二次调用从缓存获取
result2 = fibonacci(10)
3.4 闭包
00.总结
a.说明
闭包是指一个函数对象,它记住了创建时的环境,即使在外部函数已经返回后,内部函数仍然可以访问外部函数的变量。
b.特点
函数嵌套、内部函数引用外部变量、延长变量生命周期、数据封装和隐藏。
01.闭包定义
def outer_function(x):
def inner_function(y):
return x + y # 访问外部函数的变量x
return inner_function
add_five = outer_function(5)
result = add_five(3) # 8
def make_multiplier(factor):
def multiply(number):
return number * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
result1 = double(5) # 10
result2 = triple(5) # 15
02.闭包应用
# 计数器工厂
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter1 = counter()
counter2 = counter()
print(counter1()) # 1
print(counter1()) # 2
print(counter2()) # 1
# 配置管理
def config_manager(initial_config):
config = initial_config.copy()
def get_config(key):
return config.get(key)
def set_config(key, value):
config[key] = value
def update_config(new_config):
config.update(new_config)
return get_config, set_config, update_config
get_conf, set_conf, update_conf = config_manager({"debug": False})
debug_status = get_conf("debug")
set_conf("debug", True)
# 缓存机制
def memoize(func):
cache = {}
def memoized_func(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return memoized_func
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
4 面向对象
4.1 类和对象
00.总结
a.说明
类是面向对象编程的基本概念,是创建对象的蓝图。对象是类的实例,包含属性和方法。
b.类的组成
类名、属性(数据)、方法(行为)、构造函数、析构函数。
01.类的定义
a.基本语法
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"我叫{self.name},今年{self.age}岁"
b.构造方法(__init__)
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []
def add_course(self, course):
self.courses.append(course)
c.实例方法
class Calculator:
def __init__(self):
self.result = 0
def add(self, x, y):
self.result = x + y
return self.result
def clear(self):
self.result = 0
d.类变量和实例变量
class Dog:
species = "犬科" # 类变量
count = 0 # 类变量
def __init__(self, name):
self.name = name # 实例变量
Dog.count += 1
def bark(self):
return f"{self.name}汪汪叫"
02.对象创建和使用
# 创建对象
person1 = Person("张三", 25)
person2 = Person("李四", 30)
# 访问属性
print(person1.name) # 张三
print(person2.age) # 30
# 调用方法
message = person1.introduce()
print(message)
# 修改属性
person2.age = 31
print(person2.introduce())
03.访问控制
a.公有属性
class PublicExample:
def __init__(self):
self.public_attr = "公有属性"
def public_method(self):
return "公有方法"
obj = PublicExample()
print(obj.public_attr)
obj.public_method()
b.私有属性(_和__)
class PrivateExample:
def __init__(self):
self._protected_attr = "受保护属性"
self.__private_attr = "私有属性"
def _protected_method(self):
return "受保护方法"
def __private_method(self):
return "私有方法"
def get_private(self):
return self.__private_attr
obj = PrivateExample()
print(obj._protected_attr)
print(obj.get_private())
# print(obj.__private_attr) # 会报错
c.受保护属性
class ProtectedExample:
def __init__(self):
self._data = "受保护数据"
def _internal_method(self):
return "内部方法"
4.2 继承
00.总结
a.说明
继承是面向对象编程的重要特性,允许一个类继承另一个类的属性和方法,实现代码重用和层次化设计。
b.继承类型
单继承、多继承、多层继承、混合继承。
01.单继承
# 基类(父类)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name}发出声音"
def eat(self):
return f"{self.name}正在吃东西"
# 派生类(子类)
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 调用父类构造函数
self.breed = breed
def speak(self): # 重写父类方法
return f"{self.name}汪汪叫"
def fetch(self):
return f"{self.name}去捡球"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self):
return f"{self.name}喵喵叫"
def climb(self):
return f"{self.name}爬树"
02.多继承
a.MRO(方法解析顺序)
class A:
def method(self):
return "A的方法"
class B(A):
def method(self):
return "B的方法"
class C(A):
def method(self):
return "C的方法"
class D(B, C):
pass
# 查看MRO
print(D.__mro__)
d = D()
print(d.method()) # 调用B的方法
b.super() 函数
class Parent1:
def __init__(self, name):
self.name = name
print("Parent1构造函数")
class Parent2:
def __init__(self, age):
self.age = age
print("Parent2构造函数")
class Child(Parent1, Parent2):
def __init__(self, name, age, grade):
super().__init__(name) # 调用Parent1的构造函数
Parent2.__init__(self, age) # 显式调用Parent2的构造函数
self.grade = grade
print("Child构造函数")
03.方法重写
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start(self):
return f"{self.brand} {self.model}启动"
def stop(self):
return f"{self.brand} {self.model}停止"
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def start(self): # 重写父类方法
return f"{self.brand} {self.model}汽车引擎启动"
def open_trunk(self):
return "打开后备箱"
class Motorcycle(Vehicle):
def __init__(self, brand, model, type_):
super().__init__(brand, model)
self.type = type_
def start(self):
return f"{self.brand} {self.model}摩托车发动"
def wheelie(self):
return "做翘头动作"
4.3 多态
00.总结
a.说明
多态是面向对象编程的重要特性,指不同类的对象对同一方法调用产生不同的行为结果。
b.实现方式
方法重写、接口继承、鸭子类型。
01.多态示例
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
def perimeter(self):
return self.base + self.height + (self.base**2 + self.height**2)**0.5
# 多态使用
shapes = [Rectangle(5, 3), Circle(4), Triangle(3, 4)]
for shape in shapes:
print(f"面积: {shape.area()}, 周长: {shape.perimeter()}")
02.鸭子类型
class Duck:
def quack(self):
return "鸭子嘎嘎叫"
def swim(self):
return "鸭子在游泳"
class Person:
def quack(self):
return "人在模仿鸭子叫"
def swim(self):
return "人在游泳"
class Boat:
def quack(self):
return "船在鸣笛"
def swim(self):
return "船在航行"
def make_it_quack_and_swim(thing):
print(thing.quack())
print(thing.swim())
# 鸭子类型:不关心对象的具体类型,只关心它是否有相应的方法
duck = Duck()
person = Person()
boat = Boat()
make_it_quack_and_swim(duck)
make_it_quack_and_swim(person)
make_it_quack_and_swim(boat)
03.抽象基类(ABC)
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
@abstractmethod
def move(self):
pass
def sleep(self):
return "动物正在睡觉"
class Dog(Animal):
def make_sound(self):
return "汪汪叫"
def move(self):
return "狗在奔跑"
class Cat(Animal):
def make_sound(self):
return "喵喵叫"
def move(self):
return "猫在走路"
class Bird(Animal):
def make_sound(self):
return "啾啾叫"
def move(self):
return "鸟在飞翔"
# 使用抽象基类
def animal_actions(animal):
print(f"声音: {animal.make_sound()}")
print(f"移动: {animal.move()}")
print(f"休息: {animal.sleep()}")
dog = Dog()
cat = Cat()
bird = Bird()
animal_actions(dog)
animal_actions(cat)
animal_actions(bird)
# 无法直接实例化抽象类
# animal = Animal() # 会抛出TypeError
4.4 封装
00.总结
a.说明
封装是面向对象编程的核心特性之一,通过将数据和方法包装在类中,隐藏内部实现细节,提供公共接口访问。
b.特点
数据隐藏、接口统一、安全性、可维护性。
01.属性封装
a.@property
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("温度不能低于绝对零度")
self._celsius = value
temp = Temperature(25)
print(f"摄氏度: {temp.celsius}")
print(f"华氏度: {temp.fahrenheit}")
temp.celsius = 30
b.getter 和 setter
class BankAccount:
def __init__(self, initial_balance=0):
self.__balance = initial_balance
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount < 0:
raise ValueError("余额不能为负数")
self.__balance = amount
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
raise ValueError("取款金额无效")
account = BankAccount(1000)
print(f"当前余额: {account.get_balance()}")
account.deposit(500)
print(f"存款后余额: {account.get_balance()}")
4.5 特殊方法
00.总结
a.说明
特殊方法(魔术方法)是Python中以双下划线开头和结尾的方法,用于实现对象的内置行为和操作。
b.常用特殊方法
__init__、__str__、__repr__、__add__、__len__、__getitem__、__call__等。
01.构造和析构
a.__init__
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"Person {name} 创建完成")
person = Person("张三", 25)
b.__del__
class FileManager:
def __init__(self, filename):
self.filename = filename
self.file = open(filename, 'w')
print(f"文件 {filename} 已打开")
def __del__(self):
if hasattr(self, 'file') and self.file:
self.file.close()
print(f"文件 {self.filename} 已关闭")
fm = FileManager("test.txt")
del fm # 手动删除,会调用__del__
c.__new__
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if not hasattr(self, 'initialized'):
self.initialized = True
print("单例初始化")
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
02.字符串表示
a.__str__
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"《{self.title}》- {self.author}"
book = Book("Python编程", "张三")
print(book) # 调用__str__
b.__repr__
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print(repr(p)) # Point(3, 4)
print([p]) # 列表中使用repr
03.运算符重载
a.__add__、__sub__ 等
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(1, 4)
print(v1 + v2) # Vector(3, 7)
print(v1 - v2) # Vector(1, -1)
print(v1 * 2) # Vector(4, 6)
b.__eq__、__lt__ 等
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __eq__(self, other):
return self.score == other.score
def __lt__(self, other):
return self.score < other.score
def __le__(self, other):
return self.score <= other.score
def __str__(self):
return f"{self.name}: {self.score}"
s1 = Student("张三", 85)
s2 = Student("李四", 90)
s3 = Student("王五", 85)
print(s1 == s2) # False
print(s1 == s3) # True
print(s1 < s2) # True
students = [s1, s2, s3]
students.sort() # 使用__lt__排序
04.容器方法
a.__len__
class Stack:
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
stack = Stack()
stack.push(1)
stack.push(2)
print(len(stack)) # 2
b.__getitem__
class CustomList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
if isinstance(index, slice):
return CustomList(self.items[index])
return self.items[index]
def __len__(self):
return len(self.items)
cl = CustomList([1, 2, 3, 4, 5])
print(cl[2]) # 3
print(cl[1:4]) # CustomList([2, 3, 4])
c.__setitem__
class CustomDict:
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __contains__(self, key):
return key in self.data
cd = CustomDict()
cd["name"] = "张三"
print(cd["name"]) # 张三
print("name" in cd) # True
05.可调用对象
a.__call__
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor
double = Multiplier(2)
triple = Multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
06.上下文管理器
a.__enter__
b.__exit__
class Timer:
def __init__(self):
self.start_time = None
def __enter__(self):
import time
self.start_time = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
end_time = time.time()
print(f"执行时间: {end_time - self.start_time:.4f}秒")
return False
with Timer() as timer:
total = sum(range(1000000))
print(f"计算结果: {total}")
4.6 模块和包
00.总结
a.说明
模块是包含Python函数、类和变量的文件,包是包含多个模块的目录结构,用于组织和管理代码。
b.组织结构
模块化设计、层次化组织、命名空间管理、代码重用。
01.模块
a.模块导入
# 导入整个模块
import math
result = math.sqrt(16)
# 导入特定函数/类
from math import sqrt, sin
result = sqrt(16)
# 导入并重命名
import numpy as np
import pandas as pd
# 导入所有内容(不推荐)
from math import *
# 条件导入
try:
import numpy
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
b.模块搜索路径
import sys
print("模块搜索路径:")
for path in sys.path:
print(path)
# 添加自定义路径
sys.path.append('/path/to/custom/modules')
c.__name__ 属性
# my_module.py
def show_name():
print(f"模块名称: {__name__}")
if __name__ == "__main__":
print("作为主程序运行")
show_name()
else:
print("作为模块被导入")
show_name()
02.包
a.包的创建
# 包目录结构:
# mypackage/
# ├── __init__.py
# ├── module1.py
# ├── module2.py
# └── subpackage/
# ├── __init__.py
# └── module3.py
b.__init__.py
# mypackage/__init__.py
print("mypackage包被导入")
# 定义包级别的变量
VERSION = "1.0.0"
AUTHOR = "张三"
# 导入模块,使其在包级别可用
from .module1 import func1
from .module2 import Class2
c.相对导入和绝对导入
# 绝对导入
from mypackage.module1 import func1
from mypackage.subpackage.module3 import func3
# 相对导入(在包内部使用)
from .module1 import func1 # 同级模块
from ..subpackage.module3 import func3 # 上级包的子包
from . import module2 # 导入同级模块
03.常用标准库模块
# os模块 - 操作系统接口
import os
current_dir = os.getcwd()
files = os.listdir('.')
os.makedirs('new_folder', exist_ok=True)
# sys模块 - 系统相关
import sys
print(sys.version)
sys.path.append('/custom/path')
# json模块 - JSON数据处理
import json
data = {'name': '张三', 'age': 25}
json_str = json.dumps(data)
parsed_data = json.loads(json_str)
# datetime模块 - 日期时间处理
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
# collections模块 - 特殊容器
from collections import Counter, defaultdict, namedtuple
counter = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
# re模块 - 正则表达式
import re
pattern = r'\b\d{3}-\d{4}-\d{4}\b'
phone = re.search(pattern, '我的电话是123-4567-8910')
# random模块 - 随机数
import random
random_number = random.randint(1, 100)
random_choice = random.choice(['苹果', '香蕉', '橙子'])
5 高级特性
5.1 异常处理
00.总结
a.说明
异常处理是Python中处理程序运行时错误的重要机制,通过try-except结构捕获和处理异常,保证程序的健壮性。
b.异常层次结构
BaseException → Exception → ValueError, TypeError, IOError等具体异常类型。
01.异常捕获
a.try-except
# 基本异常捕获
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
# 捕获多个异常
try:
number = int(input("请输入数字: "))
result = 10 / number
except (ValueError, ZeroDivisionError):
print("输入无效或除数为零")
# 分别处理不同异常
try:
number = int(input("请输入数字: "))
result = 10 / number
except ValueError:
print("请输入有效的数字")
except ZeroDivisionError:
print("除数不能为零")
b.try-except-else
try:
number = int(input("请输入数字: "))
result = 10 / number
except ValueError:
print("输入无效")
except ZeroDivisionError:
print("除数为零")
else:
print(f"计算结果: {result}")
c.try-except-finally
def read_file(filename):
file = None
try:
file = open(filename, 'r')
content = file.read()
return content
except FileNotFoundError:
print(f"文件 {filename} 不存在")
except IOError:
print(f"读取文件 {filename} 时出错")
finally:
if file:
file.close()
print("文件已关闭")
read_file("example.txt")
02.抛出异常
a.raise 语句
def check_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age > 120:
raise ValueError("年龄不能超过120")
return True
try:
check_age(-5)
except ValueError as e:
print(f"错误: {e}")
# 重新抛出异常
def process_data(data):
try:
if not data:
raise ValueError("数据不能为空")
return len(data)
except ValueError as e:
print(f"处理数据时出错: {e}")
raise # 重新抛出异常
b.自定义异常
class CustomError(Exception):
def __init__(self, message, code=None):
super().__init__(message)
self.code = code
def __str__(self):
if self.code:
return f"[错误代码 {self.code}]: {super().__str__()}"
return super().__str__()
class InsufficientFundsError(CustomError):
def __init__(self, balance, amount):
message = f"余额不足: 余额 {balance}, 尝试提取 {amount}"
super().__init__(message, code=401)
self.balance = balance
self.amount = amount
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
03.常见异常类型
# TypeError:类型错误
try:
result = "5" + 3 # 字符串不能和整数相加
except TypeError as e:
print(f"类型错误: {e}")
# IndexError:索引越界
try:
numbers = [1, 2, 3]
print(numbers[5])
except IndexError as e:
print(f"索引错误: {e}")
# KeyError:键不存在
try:
data = {"name": "张三"}
print(data["age"])
except KeyError as e:
print(f"键错误: {e}")
# FileNotFoundError:文件不存在
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"文件不存在: {e}")
# AttributeError:属性不存在
class Person:
def __init__(self, name):
self.name = name
try:
person = Person("张三")
print(person.age) # 属性age不存在
except AttributeError as e:
print(f"属性错误: {e}")
04.上下文管理器(with)
# 使用with语句自动管理资源
with open("example.txt", "w") as file:
file.write("Hello, World!")
# 文件自动关闭
# 自定义上下文管理器
class Timer:
def __init__(self):
self.start_time = None
def __enter__(self):
import time
self.start_time = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
end_time = time.time()
print(f"执行时间: {end_time - self.start_time:.4f}秒")
return False
with Timer():
total = sum(range(1000000))
print(f"计算结果: {total}")
5.2 文件操作
00.总结
a.说明
文件操作是Python中与外部存储设备进行数据交互的重要功能,包括文件的创建、读取、写入和删除等操作。
b.文件模式
'r'读取、'w'写入、'a'追加、'r+'读写、'b'二进制模式、't'文本模式。
01.文件读写
a.打开文件
# 基本打开方式
file = open("example.txt", "r") # 只读模式
file = open("example.txt", "w") # 写入模式(覆盖)
file = open("example.txt", "a") # 追加模式
file = open("example.txt", "r+") # 读写模式
file = open("example.txt", "rb") # 二进制读取模式
# 使用encoding指定编码
file = open("chinese.txt", "r", encoding="utf-8")
b.读取文件
# 读取整个文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 按行读取
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
# 逐行读取(推荐用于大文件)
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
# 指定读取字节数
with open("example.txt", "r") as file:
chunk = file.read(1024) # 读取1024字节
c.写入文件
# 写入字符串
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python文件操作示例")
# 写入列表(每行一个元素)
lines = ["第一行", "第二行", "第三行"]
with open("lines.txt", "w") as file:
file.writelines(line + "\n" for line in lines)
# 追加内容
with open("output.txt", "a") as file:
file.write("\n追加的内容")
d.关闭文件
file = open("example.txt", "r")
try:
content = file.read()
print(content)
finally:
file.close() # 确保文件被关闭
02.文件方法
with open("example.txt", "r+") as file:
# 文件信息
print(f"文件名: {file.name}")
print(f"文件模式: {file.mode}")
# 读写位置
print(f"当前位置: {file.tell()}")
# 移动指针
file.seek(0) # 移到文件开头
file.seek(0, 2) # 移到文件末尾
# 截断文件
file.truncate(100) # 保留前100个字节
# 刷新缓冲区
file.flush()
03.with 语句
# 自动资源管理
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
content = input_file.read()
output_file.write(content.upper())
# 文件自动关闭
# 自定义上下文管理器
class FileWriter:
def __init__(self, filename, mode='w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
return False
with FileWriter("custom.txt") as file:
file.write("使用自定义上下文管理器")
04.二进制文件
# 写入二进制文件
data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'
with open("binary.dat", "wb") as file:
file.write(data)
# 读取二进制文件
with open("binary.dat", "rb") as file:
binary_data = file.read()
print(binary_data)
# 处理图片文件
def copy_image(source, destination):
with open(source, "rb") as src_file:
image_data = src_file.read()
with open(destination, "wb") as dest_file:
dest_file.write(image_data)
05.文件指针操作
with open("example.txt", "r+") as file:
# 写入一些内容
file.write("Python文件操作")
# 移动到开头
file.seek(0)
print(f"开头内容: {file.read(6)}") # Python
# 移动到特定位置
file.seek(7) # 移到第7个字节
print(f"当前位置: {file.tell()}")
# 相对移动
file.seek(0) # 回到开头
file.seek(5, 1) # 从当前位置向前移动5个字节
# 从末尾移动
file.seek(-10, 2) # 从末尾向前移动10个字节
5.3 正则表达式
00.总结
a.说明
正则表达式是一种强大的文本模式匹配工具,用于在字符串中搜索、替换和验证复杂的文本模式。
b.常用模式
字符匹配、重复模式、位置匹配、分组匹配、特殊字符类。
01.re 模块
a.match()
import re
# 从字符串开头匹配
pattern = r'hello'
text = 'hello world'
match = re.match(pattern, text)
if match:
print(f"匹配成功: {match.group()}")
# 不匹配的情况
text2 = 'world hello'
match2 = re.match(pattern, text2)
print(match2) # None
b.search()
# 在字符串中搜索模式
pattern = r'python'
text = 'I love python programming'
search = re.search(pattern, text)
if search:
print(f"找到匹配: {search.group()}")
print(f"匹配位置: {search.span()}")
c.findall()
# 找到所有匹配项
pattern = r'\d+'
text = '电话: 138-1234-5678, 邮编: 100000'
numbers = re.findall(pattern, text)
print(f"所有数字: {numbers}") # ['138', '1234', '5678', '100000']
d.sub()
# 替换匹配项
pattern = r'\b\d{4}\b'
text = '年份: 2020, 2021, 2022'
replaced = re.sub(pattern, '****', text)
print(f"替换后: {replaced}") # 年份: ****, ****, ****
02.正则表达式语法
a.元字符
# . 匹配任意字符(除换行符外)
pattern = r'p.th.n'
text = 'python and pathon'
matches = re.findall(pattern, text)
# ^ 匹配字符串开头
pattern = r'^Hello'
text1 = 'Hello World'
text2 = 'Say Hello'
print(re.match(pattern, text1)) # 匹配
print(re.match(pattern, text2)) # 不匹配
# $ 匹配字符串结尾
pattern = r'world$'
text1 = 'Hello world'
text2 = 'world Hello'
print(re.search(pattern, text1)) # 匹配
print(re.search(pattern, text2)) # 不匹配
b.字符类
# [abc] 匹配方括号中任一字符
pattern = r'[aeiou]'
text = 'hello world'
vowels = re.findall(pattern, text)
# [a-z] 匹配小写字母
pattern = r'[a-z]+'
text = 'Hello World 123'
lowercase = re.findall(pattern, text)
# [^abc] 匹配不在方括号中的字符
pattern = r'[^0-9]'
text = 'abc123def456'
non_digits = re.findall(pattern, text)
c.量词
# * 匹配0次或多次
pattern = r'ab*c'
matches = re.findall(pattern, ['ac', 'abc', 'abbc', 'abbbbc'])
# + 匹配1次或多次
pattern = r'ab+c'
matches = re.findall(pattern, ['ac', 'abc', 'abbc', 'abbbbc'])
# ? 匹配0次或1次
pattern = r'colou?r'
text = 'color and colour'
colors = re.findall(pattern, text)
# {n} 匹配恰好n次
pattern = r'\d{3}'
text = '123 4567 89'
three_digits = re.findall(pattern, text)
# {n,m} 匹配n到m次
pattern = r'\d{2,4}'
numbers = re.findall(pattern, '12 345 6789')
d.分组
# 基本分组
pattern = r'(\w+)\s+(\w+)'
text = 'John Doe'
match = re.match(pattern, text)
if match:
print(f"完整匹配: {match.group(0)}")
print(f"第一个分组: {match.group(1)}")
print(f"第二个分组: {match.group(2)}")
# 命名分组
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
text = '2023-12-25'
match = re.match(pattern, text)
if match:
print(f"年: {match.group('year')}")
print(f"月: {match.group('month')}")
print(f"日: {match.group('day')}")
03.编译正则表达式
import re
# 编译正则表达式(提高性能)
pattern = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
# 多次使用编译后的模式
emails = [
'user@example.com',
'test.email+tag@domain.co.uk',
'invalid-email',
'user@domain'
]
for email in emails:
if pattern.match(email):
print(f"有效邮箱: {email}")
else:
print(f"无效邮箱: {email}")
# 编译时添加标志
pattern = re.compile(r'python', re.IGNORECASE)
text = 'Python and python and PYTHON'
matches = pattern.findall(text)
print(f"不区分大小写的匹配: {matches}")
5.4 多线程和多进程
00.总结
a.说明
多线程和多进程是Python中实现并行处理的重要机制,多线程用于I/O密集型任务,多进程用于CPU密集型任务。
b.GIL(全局解释器锁)
Python的GIL限制同一时间只能有一个线程执行Python字节码,多进程可以绕过GIL限制。
01.多线程(threading)
a.Thread 类
import threading
import time
def worker(name):
print(f"线程 {name} 开始工作")
time.sleep(2)
print(f"线程 {name} 完成工作")
# 创建和启动线程
thread1 = threading.Thread(target=worker, args=("线程1",))
thread2 = threading.Thread(target=worker, args=("线程2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
b.Lock 锁
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock:
counter += 1
threads = []
for i in range(10):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"计数器值: {counter}")
c.线程同步
import threading
class ProducerConsumer:
def __init__(self):
self.items = []
self.max_size = 5
self.lock = threading.Lock()
self.not_empty = threading.Condition(self.lock)
self.not_full = threading.Condition(self.lock)
def produce(self, item):
with self.not_full:
while len(self.items) >= self.max_size:
self.not_full.wait()
self.items.append(item)
self.not_empty.notify()
def consume(self):
with self.not_empty:
while not self.items:
self.not_empty.wait()
item = self.items.pop(0)
self.not_full.notify()
return item
02.多进程(multiprocessing)
a.Process 类
import multiprocessing
import os
def worker(name):
print(f"进程 {name} PID: {os.getpid()}")
return f"进程 {name} 完成"
processes = []
for i in range(4):
p = multiprocessing.Process(target=worker, args=(f"Process-{i}",))
processes.append(p)
p.start()
for p in processes:
p.join()
b.进程池
from multiprocessing import Pool
def square(x):
return x * x
with Pool(processes=4) as pool:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = pool.map(square, numbers)
print(f"平方结果: {results}")
c.进程间通信
from multiprocessing import Process, Queue
def producer(queue):
for i in range(10):
queue.put(f"Item {i}")
def consumer(queue):
while True:
item = queue.get()
if item == 'DONE':
break
print(f"消费: {item}")
queue = Queue()
p1 = Process(target=producer, args=(queue,))
p2 = Process(target=consumer, args=(queue,))
p1.start()
p2.start()
p1.join()
queue.put('DONE')
p2.join()
03.协程(asyncio)
a.async/await
import asyncio
async def fetch_data(url):
print(f"开始获取 {url}")
await asyncio.sleep(1) # 模拟网络请求
print(f"完成获取 {url}")
return f"数据来自 {url}"
async def main():
urls = ['url1', 'url2', 'url3']
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
asyncio.run(main())
b.事件循环
import asyncio
async def task(name, delay):
print(f"任务 {name} 开始")
await asyncio.sleep(delay)
print(f"任务 {name} 完成")
return f"任务 {name} 结果"
async def main():
loop = asyncio.get_event_loop()
tasks = [
loop.create_task(task("A", 1)),
loop.create_task(task("B", 2)),
loop.create_task(task("C", 1))
]
results = await asyncio.gather(*tasks)
return results
asyncio.run(main())
5.5 网络编程
00.总结
a.说明
网络编程是Python中的重要应用领域,涵盖了Socket编程、HTTP请求处理和Web框架开发。
b.常用协议
TCP/IP、HTTP、HTTPS、FTP、SMTP等。
01.Socket 编程
a.TCP Socket
import socket
def tcp_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 8080))
server.listen(1)
print("TCP服务器启动,监听8080端口")
conn, addr = server.accept()
print(f"连接来自: {addr}")
data = conn.recv(1024)
conn.send(b"TCP服务器响应: " + data)
conn.close()
def tcp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 8080))
client.send(b"Hello TCP Server")
response = client.recv(1024)
print(f"服务器响应: {response.decode()}")
client.close()
b.UDP Socket
import socket
def udp_server():
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 8081))
print("UDP服务器启动,监听8081端口")
while True:
data, addr = server.recvfrom(1024)
print(f"来自 {addr}: {data.decode()}")
server.sendto(b"UDP服务器响应", addr)
def udp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello UDP Server", ('localhost', 8081))
response, addr = client.recvfrom(1024)
print(f"服务器响应: {response.decode()}")
client.close()
02.HTTP 请求
a.urllib
from urllib import request, parse
import json
# GET请求
url = 'https://api.github.com/users/python'
response = request.urlopen(url)
data = json.loads(response.read().decode())
# POST请求
url = 'https://httpbin.org/post'
params = {'key': 'value'}
data = parse.urlencode(params).encode()
req = request.Request(url, data=data, method='POST')
response = request.urlopen(req)
b.requests 库
import requests
# GET请求
response = requests.get('https://api.github.com/users/python')
user_data = response.json()
# POST请求
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', json=payload)
# 带参数的请求
params = {'q': 'python', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
03.Web 框架
a.Flask
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Flask!"
@app.route('/api/data')
def get_data():
return jsonify({'message': '这是一个API响应'})
if __name__ == '__main__':
app.run(debug=True)
b.Django
# Django项目结构通常包含:
# - settings.py (配置文件)
# - urls.py (URL路由)
# - views.py (视图函数)
# - models.py (数据模型)
# - templates/ (模板文件)
c.FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return {"message": "Item created", "item": item}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
5.6 数据处理
00.总结
a.说明
数据处理是Python中的核心功能,支持JSON、CSV、XML等多种格式的数据操作和数据库访问。
b.常用库
json、csv、xml.etree、sqlite3、pymysql、pymongo、pandas等。
01.JSON 处理
a.json.dumps()
import json
data = {
"name": "张三",
"age": 25,
"skills": ["Python", "JavaScript", "SQL"],
"address": {
"city": "北京",
"district": "海淀区"
}
}
# 转换为JSON字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 转换为紧凑格式
compact_json = json.dumps(data, separators=(',', ':'))
b.json.loads()
json_str = '{"name": "张三", "age": 25}'
parsed_data = json.loads(json_str)
print(parsed_data)
# 从文件读取JSON
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
# 写入JSON到文件
with open('output.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=2)
02.CSV 处理
a.csv 模块
import csv
# 写入CSV文件
headers = ['Name', 'Age', 'City']
rows = [
['张三', 25, '北京'],
['李四', 30, '上海'],
['王五', 28, '广州']
]
with open('people.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(headers)
writer.writerows(rows)
# 读取CSV文件
with open('people.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 使用DictReader
with open('people.csv', 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['Name']}: {row['Age']}岁, 来自{row['City']}")
03.XML 处理
a.ElementTree
import xml.etree.ElementTree as ET
# 创建XML
root = ET.Element('root')
person = ET.SubElement(root, 'person', attrib={'id': '1'})
name = ET.SubElement(person, 'name')
name.text = '张三'
age = ET.SubElement(person, 'age')
age.text = '25'
tree = ET.ElementTree(root)
tree.write('people.xml', encoding='utf-8', xml_declaration=True)
# 解析XML
tree = ET.parse('people.xml')
root = tree.getroot()
for person in root.findall('person'):
name = person.find('name').text
age = person.find('age').text
print(f"姓名: {name}, 年龄: {age}")
04.数据库操作
a.SQLite3
import sqlite3
# 创建连接
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER)
''')
# 插入数据
cursor.execute('INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
('张三', 'zhangsan@example.com', 25))
# 查询数据
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
for user in users:
print(user)
conn.commit()
conn.close()
b.MySQL(pymysql)
import pymysql
connection = pymysql.connect(
host='localhost',
user='root',
password='password',
database='test_db'
)
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
connection.close()
c.MongoDB(pymongo)
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['test_database']
collection = db['users']
# 插入文档
user = {
'name': '张三',
'email': 'zhangsan@example.com',
'age': 25,
'skills': ['Python', 'JavaScript']
}
result = collection.insert_one(user)
# 查询文档
users = collection.find({'age': {'$gt': 20}})
for user in users:
print(user)
6 实战应用
6.1 Web 开发
01.Flask 框架
a.说明
Flask 是一个轻量级的 Python Web 框架,具有简单易用、灵活扩展的特点。它提供了基本的 Web 开发工具,开发者可以根据需要添加扩展。
b.安装和配置
a.安装 Flask
---
pip install flask
---
b.基本配置:
---
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
---
c.路由:
a.基本路由定义:
---
@app.route('/')
def index():
return 'Hello, World!'
---
b.动态路由:
---
@app.route('/user/<username>')
def user_profile(username):
return f'User: {username}'
---
c.路由参数类型:
---
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
---
d.HTTP 方法:
---
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return 'Login successful'
return 'Login page'
---
d.模板:
a.模板继承:
---
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
---
---
<!-- child.html -->
{% extends 'base.html' %}
{% block title %}My Page{% endblock %}
{% block content %}
<h1>Hello {{ name }}!</h1>
<p>Welcome to my website.</p>
{% endblock %}
---
e.表单处理:
a.POST 请求处理:
---
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
session['user_id'] = user.id
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
flash('Invalid email or password', 'error')
return render_template('login.html', form=form)
---
02.Django 框架
a.说明:
Django 是一个功能完整的 Web 框架,遵循 "batteries-included" 理念,提供了完整的项目结构、ORM、管理后台、认证系统等。
b.项目结构:
a.项目创建:
---
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
---
b.目录结构:
---
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
admin.py
apps.py
models.py
views.py
tests.py
---
c.模型(Model):
a.模型定义:
---
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
published = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
---
d.视图(View):
a.函数视图:
---
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
def home(request):
posts = Post.objects.filter(published=True)[:10]
return render(request, 'myapp/home.html', {'posts': posts})
@login_required
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'myapp/post_form.html', {'form': form})
---
b.类视图:
---
from django.views.generic import ListView, DetailView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
class PostListView(ListView):
model = Post
template_name = 'myapp/post_list.html'
context_object_name = 'posts'
paginate_by = 10
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
template_name = 'myapp/post_form.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
---
e.模板(Template):
a.基础模板:
---
<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Blog{% endblock %}</title>
</head>
<body>
<nav>
<a href="{% url 'home' %}">Home</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout ({{ user.username }})</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}
</nav>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
---
03.RESTful API
a.Flask-RESTful:
a.安装:
---
pip install flask-restful
---
b.基本 API:
---
from flask import Flask
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
users = [
{'id': 1, 'name': 'Alice', 'age': 25},
{'id': 2, 'name': 'Bob', 'age': 30},
]
class UserList(Resource):
def get(self):
return users
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
parser.add_argument('age', type=int, required=True)
args = parser.parse_args()
new_user = {
'id': len(users) + 1,
'name': args['name'],
'age': args['age']
}
users.append(new_user)
return new_user, 201
api.add_resource(UserList, '/api/users')
---
b.Django REST Framework:
a.安装配置:
---
pip install djangorestframework
---
---
# settings.py
INSTALLED_APPS = [
'rest_framework',
'myapp',
]
---
b.序列化器:
---
# serializers.py
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Post
fields = '__all__'
---
c.API 视图:
---
from rest_framework import viewsets, permissions
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
---
d.URL 配置:
---
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
---
6.2 数据分析
01.NumPy
a.说明:
NumPy 是 Python 科学计算的基础库,提供了高性能的多维数组对象和相关工具。它是数据分析、机器学习等领域的核心依赖。
b.安装和导入:
a.安装:
---
pip install numpy
---
b.导入:
---
import numpy as np
---
c.数组操作:
a.数组创建:
---
import numpy as np
# 一维数组
arr1d = np.array([1, 2, 3, 4, 5])
print(f"一维数组: {arr1d}")
# 二维数组
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(f"二维数组:\n{arr2d}")
# 特殊数组
zeros_arr = np.zeros((3, 4))
ones_arr = np.ones((2, 3))
random_arr = np.random.rand(2, 3)
eye_arr = np.eye(3)
print(f"零数组:\n{zeros_arr}")
print(f"单位矩阵:\n{eye_arr}")
---
b.数组属性:
---
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"形状: {arr.shape}")
print(f"维度: {arr.ndim}")
print(f"大小: {arr.size}")
print(f"数据类型: {arr.dtype}")
---
c.数组索引和切片:
---
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 行列索引
print(f"第1行: {arr[1]}")
print(f"第2列: {arr[:, 2]}")
print(f"单个元素: {arr[1, 2]}")
# 切片
print(f"前两行: \n{arr[:2]}")
print(f"第1-2列: \n{arr[:, 1:3]}")
print(f"子数组: \n{arr[1:3, 1:3]}")
---
d.数学运算:
a.数组运算:
---
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(f"加法: {a + b}")
print(f"减法: {a - b}")
print(f"乘法: {a * b}")
print(f"除法: {a / b}")
print(f"幂运算: {a ** 2}")
# 广播运算
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"每个元素加10:\n{arr + 10}")
print(f"每个元素乘以2:\n{arr * 2}")
---
b.统计函数:
---
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f"平均值: {np.mean(arr)}")
print(f"中位数: {np.median(arr)}")
print(f"标准差: {np.std(arr)}")
print(f"方差: {np.var(arr)}")
print(f"最大值: {np.max(arr)}")
print(f"最小值: {np.min(arr)}")
print(f"求和: {np.sum(arr)}")
print(f"累积和: {np.cumsum(arr)}")
---
02.Pandas
a.说明:
Pandas 是基于 NumPy 的数据分析库,提供了高效的数据结构和数据分析工具,特别适合处理结构化数据。
b.安装和导入:
a.安装:
---
pip install pandas
---
b.导入:
---
import pandas as pd
---
c.DataFrame:
a.创建 DataFrame:
---
import pandas as pd
# 从字典创建
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 35, 40],
'city': ['New York', 'London', 'Paris', 'Tokyo'],
'salary': [50000, 60000, 70000, 80000]
}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
# 从列表创建
data = [
['Alice', 25, 'New York'],
['Bob', 30, 'London'],
['Charlie', 35, 'Paris']
]
df = pd.DataFrame(data, columns=['name', 'age', 'city'])
print(df)
# 从 CSV 文件创建
# df = pd.read_csv('data.csv')
---
b.DataFrame 操作:
---
# 基本信息
print(f"形状: {df.shape}")
print(f"列名: {df.columns.tolist()}")
print(f"数据类型:\n{df.dtypes}")
print(f"描述统计:\n{df.describe()}")
# 索引和选择
print(f"前3行:\n{df.head(3)}")
print(f"后2行:\n{df.tail(2)}")
print(f"选择列:\n{df[['name', 'age']]}")
print(f"选择行:\n{df.loc[0:2]}")
print(f"条件选择:\n{df[df['age'] > 30]}")
# 排序
print(f"按年龄排序:\n{df.sort_values('age')}")
print(f"按薪资降序:\n{df.sort_values('salary', ascending=False)}")
---
d.数据清洗:
a.处理缺失值:
---
import pandas as pd
import numpy as np
# 创建包含缺失值的 DataFrame
data = {
'name': ['Alice', 'Bob', None, 'David'],
'age': [25, None, 35, 40],
'city': ['New York', 'London', 'Paris', None],
'salary': [50000, 60000, None, 80000]
}
df = pd.DataFrame(data)
# 检查缺失值
print(f"缺失值统计:\n{df.isnull().sum()}")
# 删除缺失值
df_clean = df.dropna()
print(f"删除缺失值后:\n{df_clean}")
# 填充缺失值
df_filled = df.fillna({
'name': 'Unknown',
'age': df['age'].mean(),
'city': 'Unknown',
'salary': df['salary'].median()
})
print(f"填充缺失值后:\n{df_filled}")
---
b.处理重复值:
---
# 创建包含重复值的 DataFrame
data = {
'name': ['Alice', 'Bob', 'Alice', 'David'],
'age': [25, 30, 25, 40],
'city': ['New York', 'London', 'New York', 'Tokyo']
}
df = pd.DataFrame(data)
# 检查重复值
print(f"重复行数: {df.duplicated().sum()}")
# 删除重复值
df_unique = df.drop_duplicates()
print(f"删除重复值后:\n{df_unique}")
---
c.数据类型转换:
---
df = pd.DataFrame({
'price': ['10.5', '20.3', '15.7'],
'quantity': ['5', '10', '8'],
'date': ['2023-01-01', '2023-01-02', '2023-01-03']
})
# 转换数据类型
df['price'] = pd.to_numeric(df['price'])
df['quantity'] = df['quantity'].astype(int)
df['date'] = pd.to_datetime(df['date'])
print(f"转换后的数据类型:\n{df.dtypes}")
---
e.数据分析:
a.分组聚合:
---
data = {
'department': ['IT', 'HR', 'IT', 'Finance', 'HR', 'IT'],
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'],
'salary': [70000, 50000, 80000, 90000, 55000, 75000]
}
df = pd.DataFrame(data)
# 按部门分组
dept_stats = df.groupby('department').agg({
'salary': ['mean', 'sum', 'count'],
'name': 'count'
})
print(f"部门统计:\n{dept_stats}")
# 多重聚合
result = df.groupby('department').agg({
'salary': ['mean', 'std', 'min', 'max'],
'name': lambda x: ', '.join(x)
}).round(2)
print(f"详细统计:\n{result}")
---
b.数据透视表:
---
data = {
'region': ['North', 'South', 'North', 'East', 'South', 'East', 'North'],
'product': ['A', 'A', 'B', 'A', 'B', 'B', 'A'],
'sales': [100, 150, 200, 120, 180, 250, 300]
}
df = pd.DataFrame(data)
# 创建透视表
pivot = df.pivot_table(
values='sales',
index='region',
columns='product',
aggfunc='sum',
fill_value=0
)
print(f"销售透视表:\n{pivot}")
---
c.时间序列分析:
---
# 创建时间序列数据
dates = pd.date_range('2023-01-01', periods=100, freq='D')
sales = np.random.randint(50, 200, size=100)
df = pd.DataFrame({'date': dates, 'sales': sales})
df.set_index('date', inplace=True)
# 时间重采样
monthly_sales = df.resample('M').sum()
print(f"月销售统计:\n{monthly_sales}")
# 滚动窗口
rolling_mean = df['sales'].rolling(window=7).mean()
print(f"7日移动平均:\n{rolling_mean.head(10)}")
---
03.Matplotlib
a.说明:
Matplotlib 是 Python 最常用的数据可视化库,提供了丰富的绘图功能,可以创建各种类型的图表。
b.安装和导入:
a.安装:
---
pip install matplotlib
---
b.导入:
---
import matplotlib.pyplot as plt
import numpy as np
---
c.基本绘图:
a.线图:
---
import matplotlib.pyplot as plt
import numpy as np
# 准备数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 创建图形
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, np.cos(x), label='cos(x)', color='red', linestyle='--')
# 添加标签和标题
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.title('正弦和余弦函数')
plt.legend()
plt.grid(True)
plt.show()
---
b.散点图:
---
# 生成随机数据
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100) * 0.5
plt.figure(figsize=(8, 6))
plt.scatter(x, y, alpha=0.6, color='green')
plt.xlabel('X 变量')
plt.ylabel('Y 变量')
plt.title('散点图示例')
plt.grid(True)
plt.show()
---
c.柱状图:
---
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
plt.figure(figsize=(8, 6))
bars = plt.bar(categories, values, color=['red', 'green', 'blue', 'orange', 'purple'])
# 添加数值标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height}', ha='center', va='bottom')
plt.xlabel('类别')
plt.ylabel('数值')
plt.title('柱状图示例')
plt.show()
---
d.高级可视化:
a.子图:
---
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))
# 子图1: 线图
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x))
ax1.set_title('正弦函数')
ax1.grid(True)
# 子图2: 散点图
ax2.scatter(np.random.randn(100), np.random.randn(100))
ax2.set_title('散点图')
# 子图3: 柱状图
ax3.bar(['A', 'B', 'C'], [10, 20, 15])
ax3.set_title('柱状图')
# 子图4: 直方图
ax4.hist(np.random.randn(1000), bins=30)
ax4.set_title('直方图')
plt.tight_layout()
plt.show()
---
b.饼图:
---
sizes = [30, 25, 20, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']
colors = ['gold', 'lightcoral', 'lightskyblue', 'lightgreen', 'plum']
plt.figure(figsize=(8, 8))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f')
axes[0, 1].set_title('各地区销售额占比')
# 5.3 月度销售趋势
monthly_stats['month_short'] = monthly_stats['month'].str[5:] # 只显示月份
axes[1, 0].plot(monthly_stats['month_short'], monthly_stats['revenue']/1000000,
marker='o', linewidth=2, markersize=6)
axes[1, 0].set_title('月度销售额趋势')
axes[1, 0].set_ylabel('销售额 (百万元)')
axes[1, 0].set_xlabel('月份')
axes[1, 0].tick_params(axis='x', rotation=45)
axes[1, 0].grid(True, alpha=0.3)
# 5.4 产品-地区热力图
pivot_table = df.pivot_table(values='revenue', index='product', columns='region', aggfunc='sum')
im = axes[1, 1].imshow(pivot_table.values, cmap='YlOrRd')
axes[1, 1].set_xticks(range(len(pivot_table.columns)))
axes[1, 1].set_yticks(range(len(pivot_table.index)))
axes[1, 1].set_xticklabels(pivot_table.columns)
axes[1, 1].set_yticklabels(pivot_table.index)
axes[1, 1].set_title('产品-地区销售额热力图')
# 添加数值标签
for i in range(len(pivot_table.index)):
for j in range(len(pivot_table.columns)):
text = axes[1, 1].text(j, i, f'{pivot_table.iloc[i, j]/1000000:.1f}M',
ha="center", va="center", color="black")
plt.colorbar(im, ax=axes[1, 1], label='销售额 (元)')
plt.tight_layout()
plt.show()
# 6. 高级分析 - 相关性分析
print("\n=== 相关性分析 ===")
# 创建特征工程
df['day_of_week'] = df['date'].dt.dayofweek
df['quarter'] = df['date'].dt.quarter
df['is_weekend'] = df['day_of_week'].isin([5, 6]).astype(int)
# 计算相关性
correlation_data = df[['sales', 'revenue', 'day_of_week', 'quarter', 'is_weekend']].corr()
print("相关性矩阵:")
print(correlation_data)
# 7. 业务洞察
print("\n=== 业务洞察 ===")
# 最畅销产品
best_product = product_stats.index[0]
best_product_revenue = product_stats.loc[best_product, 'revenue']
print(f"最畅销产品: {best_product}, 收入: {best_product_revenue:,.0f} 元")
# 最佳销售地区
best_region = region_stats.index[0]
best_region_revenue = region_stats.loc[best_region, 'revenue']
print(f"最佳销售地区: {best_region}, 收入: {best_region_revenue:,.0f} 元")
# 最佳销售月份
best_month = monthly_stats.loc[monthly_stats['revenue'].idxmax(), 'month']
best_month_revenue = monthly_stats['revenue'].max()
print(f"最佳销售月份: {best_month}, 收入: {best_month_revenue:,.0f} 元")
# 周末效应
weekend_sales = df[df['is_weekend'] == 1]['sales'].mean()
weekday_sales = df[df['is_weekend'] == 0]['sales'].mean()
print(f"周末平均销量: {weekend_sales:.1f}")
print(f"工作日平均销量: {weekday_sales:.1f}")
print(f"周末销量提升: {((weekend_sales / weekday_sales - 1) * 100):.1f}%")
if __name__ == "__main__":
sales_analysis_demo()
---
6.3 机器学习
01.Scikit-learn
a.说明:
Scikit-learn 是 Python 最重要的机器学习库之一,提供了简单高效的工具用于数据挖掘和数据分析。它包含分类、回归、聚类、降维、模型选择等算法。
b.安装和导入:
a.安装:
---
pip install scikit-learn
---
b.导入:
---
import sklearn
from sklearn import datasets, model_selection, preprocessing
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
---
c.分类:
a.数据准备:
---
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载鸢尾花数据集
iris = load_iris()
X, y = iris.data, iris.target
# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)
# 特征标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(f"训练集形状: {X_train_scaled.shape}")
print(f"测试集形状: {X_test_scaled.shape}")
---
b.分类算法:
---
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
# K近邻分类器
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train_scaled, y_train)
knn_pred = knn.predict(X_test_scaled)
knn_accuracy = accuracy_score(y_test, knn_pred)
# 支持向量机
svm = SVC(kernel='rbf', random_state=42)
svm.fit(X_train_scaled, y_train)
svm_pred = svm.predict(X_test_scaled)
svm_accuracy = accuracy_score(y_test, svm_pred)
# 随机森林
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train) # 随机森林不需要标准化
rf_pred = rf.predict(X_test)
rf_accuracy = accuracy_score(y_test, rf_pred)
# 逻辑回归
lr = LogisticRegression(random_state=42)
lr.fit(X_train_scaled, y_train)
lr_pred = lr.predict(X_test_scaled)
lr_accuracy = accuracy_score(y_test, lr_pred)
print(f"KNN 准确率: {knn_accuracy:.3f}")
print(f"SVM 准确率: {svm_accuracy:.3f}")
print(f"随机森林 准确率: {rf_accuracy:.3f}")
print(f"逻辑回归 准确率: {lr_accuracy:.3f}")
# 分类报告
print("\n随机森林分类报告:")
print(classification_report(y_test, rf_pred, target_names=iris.target_names))
---
d.回归:
a.线性回归:
---
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
# 生成模拟数据
np.random.seed(42)
X = np.random.randn(100, 1) * 10
y = 2 * X.ravel() + 1 + np.random.randn(100) * 2
# 分割数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 线性回归
lr = LinearRegression()
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
# 评估
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"线性回归 MSE: {mse:.3f}")
print(f"线性回归 R²: {r2:.3f}")
print(f"回归系数: {lr.coef_[0]:.3f}")
print(f"截距: {lr.intercept_:.3f}")
---
b.多种回归算法:
---
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.ensemble import GradientBoostingRegressor
# 随机森林回归
rf_reg = RandomForestRegressor(n_estimators=100, random_state=42)
rf_reg.fit(X_train, y_train)
rf_pred = rf_reg.predict(X_test)
rf_mse = mean_squared_error(y_test, rf_pred)
# 支持向量回归
svr = SVR(kernel='rbf')
svr.fit(X_train, y_train)
svr_pred = svr.predict(X_test)
svr_mse = mean_squared_error(y_test, svr_pred)
# 梯度提升回归
gbr = GradientBoostingRegressor(n_estimators=100, random_state=42)
gbr.fit(X_train, y_train)
gbr_pred = gbr.predict(X_test)
gbr_mse = mean_squared_error(y_test, gbr_pred)
print(f"\n回归算法 MSE 对比:")
print(f"线性回归: {mse:.3f}")
print(f"随机森林: {rf_mse:.3f}")
print(f"支持向量回归: {svr_mse:.3f}")
print(f"梯度提升: {gbr_mse:.3f}")
---
e.聚类:
a.K-means 聚类:
---
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# 生成聚类数据
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
# K-means 聚类
kmeans = KMeans(n_clusters=4, random_state=42)
y_kmeans = kmeans.fit_predict(X)
centers = kmeans.cluster_centers_
print(f"聚类中心:\n{centers}")
print(f"聚类的 inertia 值: {kmeans.inertia_:.3f}")
# 手肘法确定最佳聚类数
inertias = []
K = range(1, 11)
for k in K:
kmeans_temp = KMeans(n_clusters=k, random_state=42)
kmeans_temp.fit(X)
inertias.append(kmeans_temp.inertia_)
print(f"\n不同 K 值的 inertia:")
for k, inertia in zip(K, inertias):
print(f"K={k}: {inertia:.3f}")
---
b.层次聚类:
---
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
# 层次聚类
agg = AgglomerativeClustering(n_clusters=4)
y_agg = agg.fit_predict(X)
# 绘制树状图
linkage_matrix = linkage(X, method='ward')
print("层次聚类完成")
---
c.DBSCAN 聚类:
---
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
# 生成月牙形数据
X_moons, _ = make_moons(n_samples=200, noise=0.05, random_state=42)
# DBSCAN 聚类
dbscan = DBSCAN(eps=0.3, min_samples=5)
y_dbscan = dbscan.fit_predict(X_moons)
# 统计聚类结果
n_clusters = len(set(y_dbscan)) - (1 if -1 in y_dbscan else 0)
n_noise = list(y_dbscan).count(-1)
print(f"DBSCAN 聚类数: {n_clusters}")
print(f"噪声点数: {n_noise}")
---
02.TensorFlow/PyTorch
a.说明:
TensorFlow 和 PyTorch 是两个主要的深度学习框架,提供了强大的工具来构建和训练神经网络。
b.TensorFlow:
a.安装:
---
pip install tensorflow
---
b.基础神经网络:
---
import tensorflow as tf
from tensorflow import keras
import numpy as np
# 构建简单的神经网络
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.summary()
---
c.数据准备和训练:
---
# 加载 MNIST 数据
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
# 训练模型
history = model.fit(x_train, y_train,
epochs=10,
batch_size=128,
validation_split=0.2,
verbose=1)
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"测试准确率: {test_acc:.4f}")
---
c.PyTorch:
a.安装:
---
pip install torch torchvision
---
b.基础神经网络:
---
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import torchvision.transforms as transforms
# 定义神经网络
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 10)
self.dropout = nn.Dropout(0.2)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.dropout(x)
x = torch.relu(self.fc2(x))
x = self.dropout(x)
x = self.fc3(x)
return x
# 创建模型实例
model = NeuralNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
print(model)
---
c.数据准备和训练循环:
---
# 数据准备
from torchvision import datasets
# 加载 MNIST 数据
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
test_dataset = datasets.MNIST('./data', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, batch_size=128, shuffle=False)
# 训练循环
num_epochs = 10
for epoch in range(num_epochs):
model.train()
running_loss = 0.0
correct = 0
total = 0
for batch_idx, (data, target) in enumerate(train_loader):
data = data.view(data.size(0), -1)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
train_acc = 100 * correct / total
avg_loss = running_loss / len(train_loader)
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {avg_loss:.4f}, Accuracy: {train_acc:.2f}%')
# 测试模型
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data, target in test_loader:
data = data.view(data.size(0), -1)
output = model(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
test_acc = 100 * correct / total
print(f'测试准确率: {test_acc:.2f}%')
---
03.代码示例
a.说明:
提供完整的机器学习项目示例,包括数据预处理、模型训练、评估和可视化的完整流程。
b.房价预测项目:
---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def house_price_prediction():
"""房价预测完整项目"""
# 1. 数据生成(模拟真实房价数据)
np.random.seed(42)
n_samples = 1000
# 生成特征
data = {
'area': np.random.normal(120, 40, n_samples), # 面积(平方米)
'bedrooms': np.random.choice([1, 2, 3, 4, 5], n_samples, p=[0.1, 0.2, 0.4, 0.2, 0.1]),
'bathrooms': np.random.choice([1, 2, 3, 4], n_samples, p=[0.2, 0.5, 0.2, 0.1]),
'floors': np.random.choice([1, 2, 3], n_samples, p=[0.6, 0.3, 0.1]),
'age': np.random.exponential(10, n_samples), # 房龄(年)
'location': np.random.choice(['市中心', '郊区', '近郊', '远郊'], n_samples, p=[0.3, 0.2, 0.3, 0.2]),
'parking': np.random.choice([0, 1, 2], n_samples, p=[0.2, 0.6, 0.2]),
}
df = pd.DataFrame(data)
# 生成房价(基于特征的组合)
base_price = 50000 # 基础价格
area_factor = df['area'] * 1000
bedroom_factor = df['bedrooms'] * 20000
bathroom_factor = df['bathrooms'] * 15000
floor_factor = df['floors'] * 30000
age_factor = -df['age'] * 2000 # 房龄越高价格越低
parking_factor = df['parking'] * 25000
# 地区因子
location_factor = df['location'].map({
'市中心': 100000,
'近郊': 50000,
'郊区': 20000,
'远郊': -10000
})
# 添加随机噪声
noise = np.random.normal(0, 20000, n_samples)
df['price'] = (base_price + area_factor + bedroom_factor + bathroom_factor +
floor_factor + age_factor + location_factor + parking_factor + noise)
# 确保价格为正
df['price'] = df['price'].clip(lower=50000)
print("=== 数据概览 ===")
print(f"数据形状: {df.shape}")
print(f"\n前5行数据:")
print(df.head())
print(f"\n数据描述:")
print(df.describe())
# 2. 数据预处理
print("\n=== 数据预处理 ===")
# 处理缺失值
print(f"缺失值统计:")
print(df.isnull().sum())
# 编码分类变量
le = LabelEncoder()
df['location_encoded'] = le.fit_transform(df['location'])
print(f"位置编码: {dict(zip(le.classes_, le.transform(le.classes_)))}")
# 特征选择
numeric_features = ['area', 'bedrooms', 'bathrooms', 'floors', 'age', 'parking', 'location_encoded']
X = df[numeric_features]
y = df['price']
print(f"\n特征数量: {len(numeric_features)}")
print(f"特征列表: {numeric_features}")
# 3. 数据可视化
print("\n=== 数据可视化 ===")
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
fig.suptitle('房价数据探索性分析', fontsize=16)
# 价格分布
axes[0, 0].hist(df['price'], bins=50, alpha=0.7, color='skyblue')
axes[0, 0].set_title('房价分布')
axes[0, 0].set_xlabel('价格(元)')
axes[0, 0].set_ylabel('频次')
# 面积 vs 价格
axes[0, 1].scatter(df['area'], df['price'], alpha=0.6, color='orange')
axes[0, 1].set_title('面积 vs 价格')
axes[0, 1].set_xlabel('面积(平方米)')
axes[0, 1].set_ylabel('价格(元)')
# 卧室数量 vs 价格
bedroom_price = df.groupby('bedrooms')['price'].mean()
axes[0, 2].bar(bedroom_price.index, bedroom_price.values, color='green', alpha=0.7)
axes[0, 2].set_title('卧室数量 vs 平均价格')
axes[0, 2].set_xlabel('卧室数量')
axes[0, 2].set_ylabel('平均价格(元)')
# 地区 vs 价格
location_price = df.groupby('location')['price'].mean()
axes[1, 0].bar(location_price.index, location_price.values, color='purple', alpha=0.7)
axes[1, 0].set_title('地区 vs 平均价格')
axes[1, 0].set_xlabel('地区')
axes[1, 0].tick_params(axis='x', rotation=45)
# 房龄 vs 价格
axes[1, 1].scatter(df['age'], df['price'], alpha=0.6, color='red')
axes[1, 1].set_title('房龄 vs 价格')
axes[1, 1].set_xlabel('房龄(年)')
axes[1, 1].set_ylabel('价格(元)')
# 相关性热力图
corr_data = df[numeric_features + ['price']].corr()
im = axes[1, 2].imshow(corr_data.values, cmap='coolwarm', aspect='auto')
axes[1, 2].set_xticks(range(len(corr_data.columns)))
axes[1, 2].set_yticks(range(len(corr_data.columns)))
axes[1, 2].set_xticklabels(corr_data.columns, rotation=45)
axes[1, 2].set_yticklabels(corr_data.columns)
axes[1, 2].set_title('特征相关性热力图')
# 添加相关性数值
for i in range(len(corr_data.columns)):
for j in range(len(corr_data.columns)):
text = axes[1, 2].text(j, i, f'{corr_data.iloc[i, j]:.2f}',
ha="center", va="center", color="black")
plt.colorbar(im, ax=axes[1, 2])
plt.tight_layout()
plt.show()
# 4. 数据分割和标准化
print("\n=== 数据准备 ===")
# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"训练集大小: {X_train.shape}")
print(f"测试集大小: {X_test.shape}")
# 特征标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("特征标准化完成")
# 5. 模型训练和比较
print("\n=== 模型训练和比较 ===")
models = {
'线性回归': LinearRegression(),
'岭回归': Ridge(alpha=1.0),
'Lasso回归': Lasso(alpha=1.0),
'随机森林': RandomForestRegressor(n_estimators=100, random_state=42),
'梯度提升': GradientBoostingRegressor(n_estimators=100, random_state=42)
}
results = {}
for name, model in models.items():
print(f"\n训练 {name}...")
# 训练模型
if name in ['线性回归', '岭回归', 'Lasso回归']:
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
else:
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# 评估模型
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 交叉验证
if name in ['线性回归', '岭回归', 'Lasso回归']:
cv_scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring='r2')
else:
cv_scores = cross_val_score(model, X_train, y_train, cv=5, scoring='r2')
results[name] = {
'MSE': mse,
'RMSE': rmse,
'MAE': mae,
'R2': r2,
'CV_R2_mean': cv_scores.mean(),
'CV_R2_std': cv_scores.std()
}
print(f"{name} - MSE: {mse:,.0f}, RMSE: {rmse:,.0f}, MAE: {mae:,.0f}, R²: {r2:.4f}")
print(f"{name} - 交叉验证 R²: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})")
# 6. 结果可视化
print("\n=== 模型比较 ===")
# 创建结果比较表格
results_df = pd.DataFrame(results).T
print("\n模型性能比较:")
print(results_df.round(4))
# 可视化模型性能
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle('模型性能比较', fontsize=16)
# RMSE 比较
ax1 = axes[0, 0]
bars = ax1.bar(range(len(results)), [results[name]['RMSE'] for name in results],
color='skyblue', alpha=0.7)
ax1.set_xticks(range(len(results)))
ax1.set_xticklabels(list(results.keys()), rotation=45)
ax1.set_ylabel('RMSE')
ax1.set_title('预测误差(RMSE)比较')
ax1.grid(True, alpha=0.3)
# R² 比较
ax2 = axes[0, 1]
bars = ax2.bar(range(len(results)), [results[name]['R2'] for name in results],
color='lightgreen', alpha=0.7)
ax2.set_xticks(range(len(results)))
ax2.set_xticklabels(list(results.keys()), rotation=45)
ax2.set_ylabel('R²')
ax2.set_title('决定系数(R²)比较')
ax2.grid(True, alpha=0.3)
# 交叉验证 R² 比较
ax3 = axes[1, 0]
means = [results[name]['CV_R2_mean'] for name in results]
stds = [results[name]['CV_R2_std'] for name in results]
bars = ax3.bar(range(len(results)), means, yerr=stds,
color='orange', alpha=0.7, capsize=5)
ax3.set_xticks(range(len(results)))
ax3.set_xticklabels(list(results.keys()), rotation=45)
ax3.set_ylabel('交叉验证 R²')
ax3.set_title('交叉验证 R² 比较')
ax3.grid(True, alpha=0.3)
# 最佳模型预测 vs 实际
ax4 = axes[1, 1]
best_model_name = max(results.keys(), key=lambda x: results[x]['R2'])
# 使用最佳模型进行预测
best_model = models[best_model_name]
if best_model_name in ['线性回归', '岭回归', 'Lasso回归']:
y_pred = best_model.predict(X_test_scaled)
else:
y_pred = best_model.predict(X_test)
ax4.scatter(y_test, y_pred, alpha=0.6, color='red')
ax4.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'b--', lw=2)
ax4.set_xlabel('实际价格')
ax4.set_ylabel('预测价格')
ax4.set_title(f'{best_model_name} 预测 vs 实际')
ax4.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# 7. 特征重要性分析
print("\n=== 特征重要性分析 ===")
# 使用随机森林分析特征重要性
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
feature_importance = pd.DataFrame({
'feature': numeric_features,
'importance': rf_model.feature_importances_
}).sort_values('importance', ascending=False)
print("特征重要性排序:")
print(feature_importance)
# 可视化特征重要性
plt.figure(figsize=(10, 6))
bars = plt.barh(feature_importance['feature'], feature_importance['importance'], color='steelblue', alpha=0.7)
plt.gca().invert_yaxis() # 倒序显示
plt.xlabel('重要性')
plt.title('特征重要性分析')
plt.grid(True, alpha=0.3)
# 添加数值标签
for bar in bars:
width = bar.get_width()
plt.text(width + 0.001, bar.get_y() + bar.get_height()/2,
f'{width:.3f}', ha='left', va='center')
plt.tight_layout()
plt.show()
# 8. 最终总结
print("\n=== 项目总结 ===")
print(f"数据集包含 {n_samples} 个样本和 {len(numeric_features)} 个特征")
print(f"房价范围: {df['price'].min():,.0f} - {df['price'].max():,.0f} 元")
print(f"平均房价: {df['price'].mean():,.0f} 元")
print(f"\n最佳模型: {best_model_name}")
print(f"最佳模型 R²: {results[best_model_name]['R2']:.4f}")
print(f"最佳模型 RMSE: {results[best_model_name]['RMSE']:,.0f} 元")
print(f"\n最重要的特征: {feature_importance.iloc[0]['feature']}")
return {
'data': df,
'models': models,
'results': results,
'best_model': best_model_name,
'feature_importance': feature_importance
}
if __name__ == "__main__":
project_results = house_price_prediction()
---
6.4 自动化脚本
01.系统管理
a.说明
Python 在系统管理和自动化任务中具有强大能力,可以处理文件操作、进程管理、系统监控等各种管理任务。
b.文件操作
a.基本文件操作
---
import os
import shutil
from pathlib import Path
import glob
# 基本文件操作
def file_operations_demo():
# 创建目录
os.makedirs('temp_folder', exist_ok=True)
# 写入文件
with open('temp_folder/test.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!')
# 读取文件
with open('temp_folder/test.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(f"文件内容: {content}")
# 文件信息
file_path = 'temp_folder/test.txt'
if os.path.exists(file_path):
stat = os.stat(file_path)
print(f"文件大小: {stat.st_size} 字节")
print(f"修改时间: {stat.st_mtime}")
print(f"是否为文件: {os.path.isfile(file_path)}")
print(f"是否为目录: {os.path.isdir(file_path)}")
---
b.使用 pathlib
---
def pathlib_demo():
# 创建路径对象
path = Path('temp_folder')
file_path = path / 'subfolder' / 'data.txt'
# 创建目录
file_path.parent.mkdir(parents=True, exist_ok=True)
# 写入文件
file_path.write_text('Hello, pathlib!', encoding='utf-8')
# 文件操作
print(f"文件是否存在: {file_path.exists()}")
print(f"文件名: {file_path.name}")
print(f"文件后缀: {file_path.suffix}")
print(f"父目录: {file_path.parent}")
print(f"绝对路径: {file_path.absolute()}")
---
c.批量文件操作
---
def batch_file_operations():
# 查找文件
txt_files = glob.glob('**/*.txt', recursive=True)
print(f"找到 {len(txt_files)} 个 txt 文件")
# 批量重命名
for i, file_path in enumerate(txt_files[:3], 1):
new_name = f"renamed_file_{i}.txt"
new_path = os.path.join(os.path.dirname(file_path), new_name)
if os.path.exists(file_path):
os.rename(file_path, new_path)
print(f"重命名: {file_path} -> {new_path}")
---
c.批处理:
a.文件批处理脚本:
---
import os
import shutil
from datetime import datetime
def file_organizer():
"""文件整理脚本 - 按文件类型整理文件"""
# 定义文件类型映射
file_types = {
'Images': ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
'Documents': ['pdf', 'doc', 'docx', 'txt', 'rtf'],
'Videos': ['mp4', 'avi', 'mkv', 'mov', 'wmv'],
'Audio': ['mp3', 'wav', 'flac', 'aac'],
'Archives': ['zip', 'rar', '7z', 'tar', 'gz']
}
# 目标目录
source_dir = '.'
# 创建文件夹
for folder in file_types.keys():
folder_path = os.path.join(source_dir, folder)
os.makedirs(folder_path, exist_ok=True)
# 整理文件
moved_files = 0
for filename in os.listdir(source_dir):
if os.path.isfile(os.path.join(source_dir, filename)):
# 获取文件扩展名
ext = filename.lower().split('.')[-1] if '.' in filename else ''
# 确定目标文件夹
target_folder = None
for folder, extensions in file_types.items():
if ext in extensions:
target_folder = folder
break
if target_folder:
source_path = os.path.join(source_dir, filename)
target_path = os.path.join(source_dir, target_folder, filename)
# 避免覆盖文件
if os.path.exists(target_path):
base, extension = os.path.splitext(filename)
new_filename = f"{base}_copy{extension}"
target_path = os.path.join(source_dir, target_folder, new_filename)
# 移动文件
shutil.move(source_path, target_path)
moved_files += 1
print(f"移动: {filename} -> {target_folder}/")
print(f"整理完成,共移动 {moved_files} 个文件")
---
b.磁盘使用情况分析
---
def disk_usage_analyzer():
"""磁盘使用情况分析"""
import os
def get_directory_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
total_size += os.path.getsize(filepath)
except OSError:
continue
return total_size
def format_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
i = 0
while size_bytes >= 1024 and i < len(size_name) - 1:
size_bytes /= 1024.0
i += 1
return f"{size_bytes:.2f}{size_name[i]}"
current_dir = '.'
print("磁盘使用情况分析:")
print("-" * 50)
# 分析当前目录
total_size = get_directory_size(current_dir)
print(f"总大小: {format_size(total_size)}")
# 分析子目录
print("\n子目录大小:")
for item in os.listdir(current_dir):
item_path = os.path.join(current_dir, item)
if os.path.isdir(item_path):
size = get_directory_size(item_path)
print(f"{item:30} {format_size(size):>10}")
---
d.进程管理:
a.进程监控和管理:
---
import psutil
import time
import subprocess
def process_monitor():
"""进程监控脚本"""
print("系统进程监控")
print("-" * 80)
print(f"{'PID':<8} {'进程名':<20} {'CPU%':<8} {'内存%':<8} {'状态':<10}")
print("-" * 80)
# 获取所有进程
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'status']):
try:
pid = proc.info['pid']
name = proc.info['name'][:19] # 截断长进程名
cpu = proc.info['cpu_percent']
memory = proc.info['memory_percent']
status = proc.info['status']
print(f"{pid:<8} {name:<20} {cpu:<8.1f} {memory:<8.1f} {status:<10}")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
---
b.系统信息收集
---
def system_info():
"""系统信息收集"""
print("=== 系统信息 ===")
# CPU 信息
print(f"\nCPU 核心数: {psutil.cpu_count(logical=True)}")
print(f"物理 CPU 核心数: {psutil.cpu_count(logical=False)}")
print(f"CPU 使用率: {psutil.cpu_percent(interval=1)}%")
# 内存信息
memory = psutil.virtual_memory()
print(f"\n内存总量: {memory.total / (1024**3):.2f} GB")
print(f"可用内存: {memory.available / (1024**3):.2f} GB")
print(f"内存使用率: {memory.percent}%")
# 磁盘信息
print(f"\n磁盘信息:")
for partition in psutil.disk_partitions():
try:
disk_usage = psutil.disk_usage(partition.mountpoint)
print(f"分区: {partition.device}")
print(f" 总容量: {disk_usage.total / (1024**3):.2f} GB")
print(f" 已使用: {disk_usage.used / (1024**3):.2f} GB")
print(f" 可用: {disk_usage.free / (1024**3):.2f} GB")
print(f" 使用率: {disk_usage.percent}%")
except PermissionError:
continue
---
02.Web 爬虫
a.requests
a.基本网络请求:
---
import requests
from urllib.parse import urljoin, urlparse
import time
def basic_requests_demo():
"""基本 HTTP 请求示例"""
# GET 请求
try:
response = requests.get('https://httpbin.org/get', timeout=10)
print(f"状态码: {response.status_code}")
print(f"响应头: {dict(response.headers)}")
print(f"响应内容 (前100字符): {response.text[:100]}")
except requests.RequestException as e:
print(f"请求失败: {e}")
# POST 请求
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=data)
print(f"POST 响应状态码: {response.status_code}")
# 带参数的 GET 请求
params = {'q': 'python', 'page': 1}
response = requests.get('https://httpbin.org/get', params=params)
print(f"带参数请求 URL: {response.url}")
---
b.请求头和 Cookie 处理
---
def headers_and_cookies_demo():
"""请求头和 Cookie 处理"""
# 自定义请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
}
# 使用 Session
session = requests.Session()
session.headers.update(headers)
# 设置 Cookie
cookies = {'session_id': '123456', 'user_preference': 'light'}
response = session.get('https://httpbin.org/cookies', cookies=cookies)
print(f"Cookie 测试响应: {response.json()}")
---
b.BeautifulSoup
a.HTML 解析
---
from bs4 import BeautifulSoup
import requests
import re
def html_parsing_demo():
"""HTML 解析示例"""
# 示例 HTML
html_content = """
<html>
<head>
<title>示例网页</title>
</head>
<body>
<div id="main">
<h1>主标题</h1>
<div class="article">
<h2 class="title">文章标题1</h2>
<p class="content">这是第一篇文章的内容。</p>
<div class="meta">
<span class="author">作者A</span>
<span class="date">2023-01-01</span>
</div>
</div>
<div class="article">
<h2 class="title">文章标题2</h2>
<p class="content">这是第二篇文章的内容。</p>
<div class="meta">
<span class="author">作者B</span>
<span class="date">2023-01-02</span>
</div>
</div>
</div>
<ul id="links">
<li><a href="https://example.com/page1">链接1</a></li>
<li><a href="https://example.com/page2">链接2</a></li>
<li><a href="https://example.com/page3">链接3</a></li>
</ul>
</body>
</html>
"""
# 创建 BeautifulSoup 对象
soup = BeautifulSoup(html_content, 'html.parser')
print("=== HTML 解析结果 ===")
# 基本解析
print(f"页面标题: {soup.title.string}")
print(f"页面标题标签: {soup.title.name}")
# CSS 选择器
articles = soup.select('div.article')
print(f"\n找到 {len(articles)} 篇文章:")
for i, article in enumerate(articles, 1):
title = article.select_one('.title').get_text(strip=True)
content = article.select_one('.content').get_text(strip=True)
author = article.select_one('.author').get_text(strip=True)
date = article.select_one('.date').get_text(strip=True)
print(f"\n文章 {i}:")
print(f" 标题: {title}")
print(f" 内容: {content}")
print(f" 作者: {author}")
print(f" 日期: {date}")
# 提取链接
links = soup.select('#links a')
print(f"\n找到 {len(links)} 个链接:")
for link in links:
href = link.get('href')
text = link.get_text(strip=True)
print(f" {text}: {href}")
---
b.实际网页爬取示例
---
def web_scraper_example():
"""实际网页爬取示例"""
try:
# 爬取网页(使用示例网站)
url = 'https://httpbin.org/html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# 提取所有标题
headings = {}
for level in range(1, 7):
elements = soup.select(f'h{level}')
if elements:
headings[f'h{level}'] = [elem.get_text(strip=True) for elem in elements]
print("页面标题结构:")
for level, titles in headings.items():
print(f"{level}: {titles}")
# 提取所有链接
links = []
for a_tag in soup.find_all('a', href=True):
links.append({
'text': a_tag.get_text(strip=True),
'href': a_tag['href']
})
print(f"\n找到 {len(links)} 个链接:")
for link in links[:5]: # 只显示前5个
print(f" {link['text']}: {link['href']}")
except requests.RequestException as e:
print(f"爬取失败: {e}")
---
c.Scrapy:
a.Scrapy 框架简介:
---
# 首先安装 Scrapy: pip install scrapy
# scrapy_project/spiders/example_spider.py
import scrapy
class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['https://quotes.toscrape.com']
def parse(self, response):
# 提取名言
quotes = response.css('div.quote')
for quote in quotes:
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('small.author::text').get(),
'tags': quote.css('div.tags a.tag::text').getall(),
}
# 跟进到下一页
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, self.parse)
---
b.中间件示例
---
class RandomUserAgentMiddleware:
"""随机 User-Agent 中间件"""
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36',
]
def process_request(self, request, spider):
user_agent = random.choice(self.user_agents)
request.headers.setdefault('User-Agent', user_agent)
---
03.自动化测试
a.unittest:
a.基本单元测试:
---
import unittest
import math
class MathFunctions:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
@staticmethod
def is_prime(n):
"""判断素数"""
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
class TestMathFunctions(unittest.TestCase):
"""数学函数测试类"""
def setUp(self):
"""测试前的设置"""
self.math = MathFunctions()
print("开始测试...")
def tearDown(self):
"""测试后的清理"""
print("测试完成")
def test_add(self):
"""测试加法"""
self.assertEqual(self.math.add(2, 3), 5)
self.assertEqual(self.math.add(-1, 1), 0)
self.assertEqual(self.math.add(0, 0), 0)
self.assertEqual(self.math.add(1.5, 2.5), 4.0)
def test_subtract(self):
"""测试减法"""
self.assertEqual(self.math.subtract(5, 3), 2)
self.assertEqual(self.math.subtract(1, 1), 0)
self.assertEqual(self.math.subtract(0, 5), -5)
def test_multiply(self):
"""测试乘法"""
self.assertEqual(self.math.multiply(3, 4), 12)
self.assertEqual(self.math.multiply(5, 0), 0)
self.assertEqual(self.math.multiply(-2, 3), -6)
def test_divide(self):
"""测试除法"""
self.assertEqual(self.math.divide(10, 2), 5.0)
self.assertEqual(self.math.divide(7, 2), 3.5)
self.assertEqual(self.math.divide(0, 5), 0.0)
# 测试除零异常
with self.assertRaises(ValueError):
self.math.divide(5, 0)
def test_is_prime(self):
"""测试素数判断"""
# 已知素数
self.assertTrue(self.math.is_prime(2))
self.assertTrue(self.math.is_prime(3))
self.assertTrue(self.math.is_prime(5))
self.assertTrue(self.math.is_prime(13))
self.assertTrue(self.math.is_prime(97))
# 非素数
self.assertFalse(self.math.is_prime(1))
self.assertFalse(self.math.is_prime(4))
self.assertFalse(self.math.is_prime(10))
self.assertFalse(self.math.is_prime(100))
def test_edge_cases(self):
"""测试边界情况"""
# 大数测试
self.assertEqual(self.math.add(1000000, 2000000), 3000000)
# 浮点数测试
result = self.math.add(0.1, 0.2)
self.assertAlmostEqual(result, 0.3, places=7)
if __name__ == '__main__':
# 运行测试
unittest.main(verbosity=2)
---
b.pytest:
a.pytest 示例:
---
# test_calculator.py
import pytest
import math
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
@pytest.fixture
def calculator():
"""fixture: 提供测试用的计算器实例"""
return Calculator()
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
(1.5, 2.5, 4.0),
(-2, -3, -5),
])
def test_add(calculator, a, b, expected):
"""参数化测试加法"""
assert calculator.add(a, b) == expected
@pytest.mark.parametrize("a,b,expected", [
(10, 2, 5.0),
(7, 2, 3.5),
(0, 5, 0.0),
(-6, 3, -2.0),
])
def test_divide(calculator, a, b, expected):
"""测试除法"""
assert calculator.divide(a, b) == expected
def test_divide_by_zero(calculator):
"""测试除零异常"""
with pytest.raises(ValueError, match="除数不能为零"):
calculator.divide(5, 0)
@pytest.mark.skip(reason="这个测试暂时跳过")
def test_skipped_example():
"""被跳过的测试示例"""
assert False
@pytest.mark.xfail(reason="已知失败,需要修复")
def test_expected_failure():
"""预期失败的测试"""
assert False
# test_string_operations.py
import pytest
class TestStringOperations:
"""字符串操作测试类"""
@pytest.fixture(autouse=True)
def setup(self):
"""自动应用的 fixture"""
self.test_string = "Hello, Python World!"
def test_string_length(self):
"""测试字符串长度"""
assert len(self.test_string) == 20
def test_string_methods(self):
"""测试字符串方法"""
assert self.test_string.upper() == "HELLO, PYTHON WORLD!"
assert self.test_string.lower() == "hello, python world!"
assert self.test_string.startswith("Hello")
assert self.test_string.endswith("World!")
assert "Python" in self.test_string
@pytest.mark.parametrize("substring,expected", [
("Hello", True),
("Python", True),
("World", True),
("java", False),
("", True), # 空字符串总是存在
])
def test_string_contains(self, substring, expected):
"""测试字符串包含关系"""
assert (substring in self.test_string) == expected
# conftest.py
import pytest
import tempfile
import os
@pytest.fixture
def temp_file():
"""临时文件 fixture"""
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
f.write("test content")
temp_path = f.name
yield temp_path
# 清理临时文件
if os.path.exists(temp_path):
os.unlink(temp_path)
@pytest.fixture
def sample_data():
"""示例数据 fixture"""
return {
'users': [
{'id': 1, 'name': 'Alice', 'age': 25},
{'id': 2, 'name': 'Bob', 'age': 30},
{'id': 3, 'name': 'Charlie', 'age': 35},
],
'products': [
{'id': 1, 'name': 'Laptop', 'price': 999.99},
{'id': 2, 'name': 'Mouse', 'price': 29.99},
]
}
---
04.代码示例
a.说明:
提供完整的自动化脚本示例,包括系统管理、Web 爬虫和自动化测试的综合应用。
b.综合自动化脚本示例:
---
import os
import sys
import requests
from bs4 import BeautifulSoup
import json
import time
from datetime import datetime
import sqlite3
import unittest
from pathlib import Path
import schedule
import logging
# 设置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('automation.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class DataCollector:
"""数据收集器 - 爬取新闻数据"""
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
self.db_path = 'news_data.db'
self.init_database()
def init_database(self):
"""初始化数据库"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS news (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT,
url TEXT UNIQUE,
source TEXT,
publish_time DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
logger.info("数据库初始化完成")
def fetch_news_data(self):
"""获取新闻数据(模拟)"""
# 这里使用模拟数据,实际应用中应该从真实网站爬取
mock_news = [
{
'title': 'Python 3.12 新特性发布',
'content': 'Python 3.12 带来了许多新特性,包括性能优化和新的语法糖...',
'url': 'https://example.com/news/python312',
'source': 'TechNews',
'publish_time': datetime.now().isoformat()
},
{
'title': '人工智能在医疗领域的应用',
'content': 'AI 技术正在革新医疗行业,从诊断到治疗都有重大突破...',
'url': 'https://example.com/news/ai-medical',
'source': 'MedicalTimes',
'publish_time': datetime.now().isoformat()
},
{
'title': '云计算市场规模持续增长',
'content': '根据最新报告,全球云计算市场预计将在未来五年内翻倍...',
'url': 'https://example.com/news/cloud-computing',
'source': 'BusinessDaily',
'publish_time': datetime.now().isoformat()
}
]
logger.info(f"获取到 {len(mock_news)} 条新闻数据")
return mock_news
def save_to_database(self, news_list):
"""保存数据到数据库"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
saved_count = 0
for news in news_list:
try:
cursor.execute('''
INSERT OR IGNORE INTO news (title, content, url, source, publish_time)
VALUES (?, ?, ?, ?, ?)
''', (
news['title'],
news['content'],
news['url'],
news['source'],
news['publish_time']
))
if cursor.rowcount > 0:
saved_count += 1
except sqlite3.Error as e:
logger.error(f"保存新闻失败: {e}")
conn.commit()
conn.close()
logger.info(f"成功保存 {saved_count} 条新闻到数据库")
return saved_count
class FileOrganizer:
"""文件整理器"""
def __init__(self, target_dir='.'):
self.target_dir = Path(target_dir)
self.file_types = {
'Images': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'],
'Documents': ['pdf', 'doc', 'docx', 'txt', 'rtf', 'xlsx', 'pptx'],
'Videos': ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'],
'Audio': ['mp3', 'wav', 'flac', 'aac', 'ogg'],
'Archives': ['zip', 'rar', '7z', 'tar', 'gz'],
'Code': ['py', 'js', 'html', 'css', 'java', 'cpp', 'c']
}
class AutomationManager:
"""自动化管理器"""
def __init__(self):
self.data_collector = DataCollector()
self.file_organizer = FileOrganizer()
self.automation_tester = AutomationTester()
def run_data_collection(self):
"""运行数据收集任务"""
logger.info("开始数据收集任务...")
news_data = self.data_collector.fetch_news_data()
saved_count = self.data_collector.save_to_database(news_data)
return saved_count
def run_file_organization(self):
"""运行文件整理任务"""
logger.info("开始文件整理任务...")
moved_count = self.file_organizer.organize_files()
self.file_organizer.generate_report()
return moved_count
def run_tests(self):
"""运行自动化测试"""
logger.info("开始自动化测试...")
return self.automation_tester.run_all_tests()
def run_daily_task(self):
"""运行日常自动化任务"""
logger.info("开始日常自动化任务...")
try:
# 1. 数据收集
saved_news = self.run_data_collection()
# 2. 文件整理(每周执行一次)
current_day = datetime.now().weekday()
moved_files = 0
if current_day == 0: # 周一
moved_files = self.run_file_organization()
# 3. 自动化测试
test_results = self.run_tests()
# 生成日常报告
daily_report = {
'date': datetime.now().isoformat(),
'tasks_completed': {
'data_collection': saved_news,
'file_organization': moved_files,
'tests': test_results['success_rate']
},
'status': 'SUCCESS'
}
report_file = Path('daily_report.json')
with open(report_file, 'w', encoding='utf-8') as f:
json.dump(daily_report, f, ensure_ascii=False, indent=2)
logger.info("日常自动化任务完成")
return daily_report
except Exception as e:
logger.error(f"日常任务执行失败: {e}")
return {'status': 'FAILED', 'error': str(e)}
def main():
"""主函数"""
logger.info("启动自动化系统...")
# 创建自动化管理器
manager = AutomationManager()
# 如果有命令行参数,立即执行任务
if len(sys.argv) > 1:
if sys.argv[1] == 'collect':
manager.run_data_collection()
elif sys.argv[1] == 'organize':
manager.run_file_organization()
elif sys.argv[1] == 'test':
manager.run_tests()
elif sys.argv[1] == 'all':
manager.run_daily_task()
else:
print("可用参数: collect, organize, test, all")
else:
# 设置定时任务
schedule.every().day.at("09:00").do(manager.run_daily_task)
schedule.every().monday.at("10:00").do(manager.run_file_organization)
schedule.every().sunday.at("23:00").do(manager.run_tests)
logger.info("定时任务已设置,按 Ctrl+C 退出")
# 运行调度器
while True:
schedule.run_pending()
time.sleep(60) # 每分钟检查一次
if __name__ == "__main__":
main()
---