解包
序列解包
可以将序列中的元素分别赋值给多个变量的操作。
# 解包列表
fruits = ['apple', 'banana', 'cherry']
fruit1, fruit2, fruit3 = fruits
print(fruit1) # 输出:apple
print(fruit2) # 输出:banana
print(fruit3) # 输出:cherry
# 解包元组
point = (3, 4)
x, y = point
print(x) # 输出:3
print(y) # 输出:4
扩展解包序列(*
)
可以将一个序列中的元素赋值给多个变量,并且还可以将多余的元素放在一个列表中
# 扩展解包
numbers = [1, 2, 3, 4, 5, 6]
first, second, *rest = numbers
print(first) # 输出:1
print(second) # 输出:2
print(rest) # 输出:[3, 4, 5, 6]
# 扩展解包和解包结合使用
fruits = ['apple', 'banana', 'cherry']
fruit1, *rest, fruit2 = fruits
print(fruit1) # 输出:apple
print(fruit2) # 输出:cherry
print(rest) # 输出:['banana']
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list = [*list1, *list2]
print(list) # 输出:[1, 2, 3, 4, 5, 6]
扩展解包字典(**
)
# 使用 ** 扩展字典
dict1 = {"name": "Alice", "age": 30}
dict2 = {"country": "USA"}
dict1 = {**dict1, **dict2}
print(dict1) # 输出:{'name': 'Alice', 'age': 30, 'country': 'USA'}
def advanced_example(*args, **kwargs):
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key}: {value}")