第十四篇:list 与 tuple——有序集合的增删改查、切片、排序详解
前言
Python 提供了多种内置数据结构,其中**列表(list)和元组(tuple)**是最常用的有序集合。本文全面讲解 list 和 tuple 的各种操作。
列表(list)基础
创建方式
empty = []
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True, None]
matrix = [[1, 2, 3], [4, 5, 6]]
len() 函数
print(len([1, 2, 3])) # 3
print(len([[1, 2], [3, 4]])) # 2
list 的基本操作
索引访问
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[-1]) # date
# print(fruits[10]) # IndexError!
切片操作
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4]
print(nums[:3]) # [0, 1, 2]
print(nums[7:]) # [7, 8, 9]
print(nums[::2]) # [0, 2, 4, 6, 8]
print(nums[::-1]) # 反转 [9, 8, ..., 0]
copy = nums[:] # 浅拷贝
添加元素
fruits.append("cherry") # 末尾添加单个
fruits.insert(0, "avocado") # 指定位置插入
fruits.extend(["date", "elderberry"]) # 批量追加
删除元素
fruits.remove("banana") # 按值删除
last = fruits.pop() # 弹出最后一个
first = fruits.pop(0) # 弹出指定位置
del fruits[0] # 按索引删除
fruits.clear() # 清空列表
修改与查找
fruits[1] = "blueberry"
fruits.count(85) # 统计次数
fruits.index(92) # 查找位置
print(85 in fruits) # 成员检查
列表排序
sort() vs sorted()
| 特性 | list.sort() |
sorted(iterable) |
|---|---|---|
| 返回值 | None(原地) |
新列表(不变) |
| 适用对象 | 仅列表 | 任何可迭代对象 |
nums = [3, 1, 4, 1, 5]
names = ["Charlie", "Alice", "Bob"]
nums.sort()
names.sort(key=str.lower)
result = sorted(names, reverse=True)
key 参数自定义排序
words = ["banana", "pie", "apple"]
words.sort(key=len)
students.sort(key=lambda x: x["score"])
列表推导式
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(1, 11) if x % 2 == 0] # [2, 4, 6, 8, 10]
products = [f"{c}-{s}" for c in colors for s in sizes]
元组(tuple)
创建与不可变性
one_element = (42,) # 注意逗号!
tup = 1, 2, 3 # 隐式元组
point = (10, 20)
# point[0] = 15 # TypeError!
container = ([1, 2], [3, 4])
container[0].append(5) # ✅ 列表本身可变
元组的应用场景
def divide(a, b):
return a // b, a % b # 返回多个值
location_map = {("北京", 39.9): "首都机场"} # 作为字典键
RGB_COLOR = (255, 99, 71) # 保护数据不被修改
list vs tuple 对比
| 特性 | list | tuple |
|---|---|---|
| 语法 | [1, 2, 3] |
(1, 2, 3) |
| 可变性 | ✅ 可变 | ❌ 不可变 |
| 内存 | 略高 | 略低 |
| 安全性 | 低 | 高 |
| 用途 | 频繁增删改 | 固定不变的集合 |
namedtuple 增强语义
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x) # 10 — 可用属性名访问
实战示例
成绩管理系统
scores.sort(key=lambda x: x[1], reverse=True)
avg = sum(s for _, s in scores) / len(scores)
去重并保持顺序
def unique_ordered(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
矩阵转置
transposed = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
总结
- list 基础 — 创建、len()、索引访问
- 增删改查 — append/insert/extend/remove/pop/del/index/count
- 切片 — [start:end:step]、反转、浅拷贝
- 排序 — sort()/sorted(),reverse 和 key 参数
- 列表推导式 — 简洁高效的创建方式
- tuple 不可变性 — 适合保护数据和作为 dict 键
- list vs tuple — 可变用 list,不可变用 tuple
- 实用技巧 — namedtuple、解包赋值、矩阵操作
下一篇文章将深入讲解条件判断:if-elif-else 与 match-case 模式匹配。
本文是 Python 教程系列的第十四篇。
