第 3 章 容器:列表、元组、字典与集合
Python 内置四大容器,是一切代码的基石:
| 类型 | 语法 | 有序 | 可变 | 重复 | 典型用途 |
|---|
| 列表 list | [1, 2, 3] | ✅ | ✅ | ✅ | 顺序数据集合 |
| 元组 tuple | (1, 2, 3) | ✅ | ❌ | ✅ | 不可变记录、多返回值 |
| 字典 dict | {"a": 1} | ✅(3.7+ 按插入序) | ✅ | 键不重复 | 键值映射 |
| 集合 set | {1, 2, 3} | ❌ | ✅ | ❌ | 去重、成员判断、集合运算 |
3.1 列表 list
创建与访问
nums = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, [4, 5]]
empty = []
nums[0]
nums[-1]
nums[1:4]
len(nums)
增删改
nums.append(6)
nums.insert(0, 0)
nums.extend([7, 8])
nums.pop()
nums.pop(0)
nums.remove(3)
del nums[0]
nums.clear()
nums[0] = 99
常用操作
nums.sort()
nums.sort(reverse=True)
sorted(nums)
words.sort(key=len)
nums.reverse()
nums.index(3)
nums.count(3)
3 in nums
sum(nums); max(nums); min(nums)
关键陷阱:列表是引用
a = [1, 2, 3]
b = a
b.append(4)
print(a)
c = a.copy()
c.append(5)
print(a)
m = [[1, 2], [3, 4]]
m2 = m.copy()
m2[0][0] = 99
print(m[0][0])
import copy
m3 = copy.deepcopy(m)
3.2 元组 tuple
point = (3, 4)
single = (42,)
not_tuple = (42)
x, y = point
a, *rest = [1, 2, 3, 4]
元组不可变(不能增删改元素),因此:
t[0] = 1 会抛 TypeError。注意:元组里的可变对象内容仍可变,如 t = ([1], 2) 时 t[0].append(3) 合法。
3.3 字典 dict
增删改查
user = {"name": "Alice", "age": 25}
user["name"]
user.get("email")
user.get("email", "未填写")
user["email"] = "a@x.com"
del user["age"]
user.pop("email")
"name" in user
遍历
for key in user:
print(key)
for value in user.values(): ...
for k, v in user.items():
print(k, v)
常用方法
d = {"a": 1, "b": 2}
d.update({"c": 3})
d.setdefault("a", 99)
d | {"d": 4}
list(d.keys())
键的要求
键必须是可哈希(不可变)类型:str、int、tuple 等可以;list、dict、set 不行。值则任意。
3.4 集合 set
s = {1, 2, 3}
empty = set()
s.add(4)
s.discard(10)
s.pop()
{1, 2, 2, 3}
list(set([1, 2, 2, 3]))
集合运算(数学意义)
a = {1, 2, 3}
b = {2, 3, 4}
a | b
a & b
a - b
a ^ b
a <= b
成员判断 x in set 是 O(1)(哈希实现),大列表频繁判断时转成集合能显著提速。
3.5 推导式(Comprehension)—— Pythonic 精髓
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
matrix_t = [[row[i] for row in matrix] for i in range(3)]
d = {w: len(w) for w in ["apple", "banana"]}
uniq_lens = {len(w) for w in ["a", "bb", "cc"]}
total = sum(x**2 for x in range(1_000_000))
建议:推导式不超过两层嵌套;更复杂时改用普通 for 循环,可读性优先。
3.6 可变 vs 不可变:贯穿全章的线索
def add(x, items=[]):
items.append(x)
return items
def add(x, items=None):
if items is None:
items = []
items.append(x)
return items
本章小结:记住四种容器的"有序/可变/重复"矩阵;警惕引用共享,需要独立副本时 copy(),嵌套时 deepcopy();推导式要练到顺手;函数默认参数永远别用可变对象。
下一章:控制流——条件、循环与匹配。