Python序列解包
序列解包将序列元素分解到多个变量,支持扩展解包和字典解包。
基本解包
元组解包
Python
coordinates = (10, 20)
x, y = coordinates
print(x, y) # 10 20
列表解包
Python
values = [1, 2, 3]
a, b, c = values
print(a, b, c) # 1 2 3
字符串解包
Python
s = "abc"
x, y, z = s
print(x, y, z) # a b c
变量交换
Python
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
扩展解包(*)
收集剩余元素
Python
values = [1, 2, 3, 4, 5]
first, *rest = values
print(first) # 1
print(rest) # [2, 3, 4, 5]
*head, last = values
print(head) # [1, 2, 3, 4]
print(last) # 5
first, *middle, last = values
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
忽略中间元素
Python
values = [1, 2, 3, 4, 5]
first, _, _, _, last = values # 用 _ 忽略
print(first, last) # 1 5
# 使用扩展解包更简洁
first, *_, last = values
print(first, last) # 1 5
分割列表
Python
data = [1, 2, 3, 4, 5, 6]
left, *right = data
print(left) # 1
print(right) # [2, 3, 4, 5, 6]
字典解包(**)
函数调用解包
Python
def greet(name, age, city):
print(f"{name}, {age}, {city}")
params = {"name": "Alice", "age": 25, "city": "Beijing"}
greet(**params) # Alice, 25, Beijing
# 等价于
greet(name="Alice", age=25, city="Beijing")
合并字典
Python
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
# Python 3.9+ 合并运算符
merged1 = dict1 | dict2
# Python 3.5+ 解包合并
merged2 = {**dict1, **dict2}
print(merged2) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
带默认值合并
Python
defaults = {"host": "localhost", "port": 3306}
user_config = {"port": 3307}
# 用户配置覆盖默认值
config = {**defaults, **user_config}
print(config) # {'host': 'localhost', 'port': 3307}
函数参数解包
列表解包为位置参数
Python
def add(a, b, c):
return a + b + c
values = [1, 2, 3]
print(add(*values)) # 6
元组解包为位置参数
Python
def power(base, exponent):
return base ** exponent
params = (2, 3)
print(power(*params)) # 8
实际应用
循环解包
Python
# 解包嵌套序列
pairs = [(1, "a"), (2, "b"), (3, "c")]
for num, letter in pairs:
print(f"{num}: {letter}")
# 1: a
# 2: b
# 3: c
字典遍历解包
Python
d = {"a": 1, "b": 2, "c": 3}
for key, value in d.items():
print(f"{key} = {value}")
函数返回多值解包
Python
def get_info():
return "Alice", 25, "Beijing"
name, age, city = get_info()
print(name, age, city) # Alice 25 Beijing
文件读取解包
Python
# CSV 行解包
line = "Alice,25,Beijing"
name, age, city = line.split(",")
print(name, age, city) # Alice 25 Beijing
解包注意事项
元素数量必须匹配
Python
values = [1, 2, 3]
# a, b = values # ValueError:太多元素
# a, b, c, d = values # ValueError:元素不足
# 使用 * 解决
a, b, *rest = values
print(a, b, rest) # 1 2 [3]
* 只能出现一次
Python
values = [1, 2, 3, 4, 5]
# *a, *b, c = values # SyntaxError
# 正确用法
a, *b, c = values
print(a, b, c) # 1 [2, 3, 4] 5
解包类型对比
| 解包类型 | 符号 | 适用对象 | 用途 |
|---|---|---|---|
| 基本解包 | 无 | 列表、元组、字符串 | 分配到变量 |
| 扩展解包 | * | 列表、元组、字符串 | 收集剩余元素 |
| 字典解包 | ** | 字典 | 函数参数、合并字典 |
要点总结
- 基本解包要求元素数量与变量数量匹配
- 收集剩余元素为列表,只能使用一次
- ** 解包字典为关键字参数或合并字典
- 常用于变量交换、循环遍历、函数调用
- 使用 _ 忽略不需要的元素
📝 发现内容有误?点击此处直接编辑