# 示例代码:使用 * 进行解包
# 1. 列表解包
def sum_all(*args):
"""函数接受任意数量的参数,并返回它们的和"""
return sum(args)
# 调用函数,传递多个参数
result = sum_all(1, 2, 3, 4, 5)
print(f"Sum of all numbers: {result}") # 输出: Sum of all numbers: 15
# 2. 字典解包
def greet(name, greeting="Hello"):
"""函数接受名字和问候语,默认问候语为 'Hello'"""
print(f"{greeting}, {name}!")
# 使用字典解包传递参数
params = {"name": "Alice", "greeting": "Hi"}
greet(**params) # 输出: Hi, Alice!
# 3. 列表解包到多个变量
numbers = [1, 2, 3, 4, 5]
*first_three, last_two, last_one = numbers
print(f"First three numbers: {first_three}") # 输出: First three numbers: [1, 2, 3]
print(f"Last two numbers: {last_two}, {last_one}") # 输出: Last two numbers: 4, 5
* 可以用于解包列表、元组等可迭代对象,** 可以用于解包字典。上一篇:python dict 遍历
下一篇:pythonwhile循环语句
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站