文章目录
- 1 列表(List)
- 1.1 列表常用方法
- 1.2 列表的特殊用途
- 1.2.1 实现堆栈(后进先出)
- 1.2.2 实现队列(先进先出)
- 1.3 列表推导式
- 1.4 嵌套列表推导式
- 2 del 语句
- 3 元组(Tuple)
- 4 集合(Set)
- 4.1 集合操作
- 4.2 集合推导式
- 5 字典(Dictionary)
- 5.1 字典基本操作
- 5.2 字典创建方式
- 5.3 字典遍历
- 6 循环技巧
- 6.1 遍历字典
- 6.2 带索引遍历序列
- 6.3 同时遍历多个序列
- 6.4 反向遍历
- 6.5 排序遍历
- 7 序列比较
1 列表(List)
列表是 Python 中最常用的数据结构之一,是有序、可变的元素集合,支持多种操作方法。
1.1 列表常用方法
方法 | 功能描述 |
---|---|
list.append(x) | 在列表末尾添加元素 x |
list.extend(iterable) | 扩展列表,添加可迭代对象的所有元素 |
list.insert(i, x) | 在索引 i 处插入元素 x |
list.remove(x) | 删除第一个值为 x 的元素 |
list.pop([i]) | 移除并返回索引 i 处的元素(默认最后一个) |
list.clear() | 清空列表 |
list.index(x[, start[, end]]) | 返回 x 第一次出现的索引 |
list.count(x) | 统计 x 在列表中出现的次数 |
list.sort(key=None, reverse=False) | 就地排序列表 |
list.reverse() | 反转列表元素 |
list.copy() | 返回列表的浅拷贝 |
示例:
fruits = ['orange', 'apple', 'pear', 'banana']
print(fruits.count('apple')) # 1
print(fruits.index('banana')) # 3fruits.append('grape')
fruits.sort()
print(fruits) # ['apple', 'banana', 'grape', 'orange', 'pear']fruits.reverse()
print(fruits) # ['pear', 'orange', 'grape', 'banana', 'apple']
1.2 列表的特殊用途
1.2.1 实现堆栈(后进先出)
stack = [3, 4, 5]
stack.append(6) # 入栈
stack.append(7)
print(stack) # [3, 4, 5, 6, 7]print(stack.pop()) # 7(出栈)
print(stack) # [3, 4, 5, 6]
1.2.2 实现队列(先进先出)
列表作为队列效率较低,推荐使用collections.deque
:
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # 入队
queue.append("Graham")print(queue.popleft()) # 'Eric'(出队)
print(queue) # deque(['John', 'Michael', 'Terry', 'Graham'])
1.3 列表推导式
简洁创建列表的方式,格式:[表达式 for 变量 in 可迭代对象 if 条件]
示例:
# 创建平方列表
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# 过滤偶数
even_numbers = [x for x in range(20) if x % 2 == 0]
print(even_numbers) # [0, 2, 4, ..., 18]# 处理字符串列表
words = [' apple', 'banana ', ' cherry ']
stripped = [word.strip() for word in words]
print(stripped) # ['apple', 'banana', 'cherry']
1.4 嵌套列表推导式
用于处理复杂结构,如矩阵转置:
# 3x4矩阵
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],
]# 转置矩阵(行变列)
transposed = [[row[i] for row in matrix] for i in range(4)]
print(transposed) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
2 del 语句
用于删除列表元素、切片或变量:
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0] # 删除索引0的元素
print(a) # [1, 66.25, 333, 333, 1234.5]del a[2:4] # 删除切片
print(a) # [1, 66.25, 1234.5]del a[:] # 清空列表
print(a) # []del a # 删除变量a
3 元组(Tuple)
元组是有序、不可变的元素集合,用逗号分隔,通常用圆括号包裹。
- 不可变:创建后不能修改元素
- 可包含任意类型元素,包括可变对象
- 支持索引和切片操作
- 可用于打包和解包
示例:
t = 12345, 54321, 'hello!' # 元组打包
print(t[0]) # 12345# 元组嵌套
u = t, (1, 2, 3, 4, 5)
print(u) # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))# 元组解包
x, y, z = t
print(x, y, z) # 12345 54321 hello!# 单元素元组(注意逗号)
singleton = 'hello',
print(singleton) # ('hello',)
4 集合(Set)
集合是无序、不重复的元素集合,支持数学集合运算。
4.1 集合操作
basket = {'apple', 'orange', 'apple', 'pear'}
print(basket) # {'orange', 'pear', 'apple'}(自动去重)# 成员检测
print('orange' in basket) # True# 集合运算
a = set('abracadabra')
b = set('alacazam')
print(a - b) # 差集:{'r', 'd', 'b'}
print(a | b) # 并集:{'a','c','r','d','b','m','z','l'}
print(a & b) # 交集:{'a', 'c'}
print(a ^ b) # 对称差集:{'r','d','b','m','z','l'}
4.2 集合推导式
# 创建不包含某些元素的集合
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a) # {'r', 'd'}
5 字典(Dictionary)
字典是键值对的无序集合,键必须唯一且不可变,值可以是任意类型。
5.1 字典基本操作
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127 # 添加键值对
print(tel) # {'jack': 4098, 'sape': 4139, 'guido': 4127}print(tel['jack']) # 4098(访问值)del tel['sape'] # 删除键值对
print(list(tel)) # ['jack', 'guido'](获取键列表)
5.2 字典创建方式
# 1. 直接创建
d1 = {'name': 'Alice', 'age': 30}# 2. 使用dict()构造函数
d2 = dict([('name', 'Bob'), ('age', 25)])# 3. 字典推导式
d3 = {x: x*2 for x in range(3)} # {0:0, 1:2, 2:4}# 4. 关键字参数
d4 = dict(name='Charlie', age=35)
5.3 字典遍历
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): # 同时获取键和值print(k, v)
6 循环技巧
6.1 遍历字典
for k, v in knights.items():print(k, v)
6.2 带索引遍历序列
for i, v in enumerate(['tic', 'tac', 'toe']):print(i, v) # 0 tic, 1 tac, 2 toe
6.3 同时遍历多个序列
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):print(f"What is your {q}? It is {a}.")
6.4 反向遍历
for i in reversed(range(1, 10, 2)):print(i) # 9,7,5,3,1
6.5 排序遍历
basket = ['apple', 'orange', 'apple', 'pear']
for f in sorted(set(basket)): # 去重并排序print(f) # apple, banana, orange, pear
7 序列比较
序列比较使用字典式顺序:
- 比较对应位置元素,直到找到不同元素
- 短序列是长序列的前缀则短序列更小
- 支持同类型序列比较
(1, 2, 3) < (1, 2, 4) # True
[1, 2, 3] < [1, 2, 4] # True
'ABC' < 'C' < 'Pascal' < 'Python' # True
(1, 2, 3) == (1.0, 2.0, 3.0) # True