Python解包

文章摘要

Bpple-GPT

*arg参数

*args 用于传递任意数量的位置参数。* 表示将所有传入的非关键字参数(位置参数)收集为一个元组。

 def my_function(*args):
     for arg in args:
         print(arg)

几个简单的例子传递多个值,加在一起

求和函数

 def add_all(*args):
     return sum(args)
 ​
 res = add_all(1, 2, 3, 4, 5)
 print(res)
 #15

计算平均数

 def calculate_average(*grades):
     if grades:
         return sum(grades) / len(grades)
     else:
         return 0
 ​
 print(calculate_average(80, 90, 70))      # 输出:80.0
 print(calculate_average(100, 95, 85, 90)) # 输出:92.5

拼接字符串

 def concatenate(*args):
     return " ".join(args)
 ​
 print(concatenate("Hello", "world", "!"))       # 输出:Hello world !
 print(concatenate("Python", "is", "fun"))       # 输出:Python is fun

四则运算

这个稍微复杂一点

 #实现四则运算
 def operations(op, *args):
     if op == '+':
         return sum(args)
     if op == '-':
         return args[0] - sum(args[1:])
     if op == '*':
         result = 1
         for i in args:
             result *= i
         return result
     if op == '/':
         result = args[0]
         for i in args[1:]:
             result /= i
         return result
     return None
 ​
 print(operations('+', 1, 2, 3, 4, 5))  # 15
 print(operations('-', 1, 2, 3, 4, 5))  # -13
 print(operations('*', 1, 2, 3, 4, 5))  # 120
 print(operations('/', 1, 2, 3, 4, 5))  # 0.008333333333333333

这个主要加了一个额外的说明参数

**kwargs可变关键字参数

**kwargs 用于接收任意数量的关键字参数,并将它们存储在一个字典中。** 将所有关键字参数收集为一个字典

基本语法:

 def my_function(**kwargs):
     for key, value in kwargs.items():
         print(f"{key} = {value}")

一个例子

 def introduce(**kwargs):
     for key, value in kwargs.items():
         print(f"{key}: {value}")
 ​
 introduce(name="Alice", age=25, city="New York")
 # 输出:
 # name: Alice
 # age: 25
 # city: New York

解包

解包(Unpacking),将一个可迭代对象(例如列表、元组或字典)中的元素分解为单独的值,然后传递给函数或者赋值给变量

通常使用 ***实现

下面这个例子使用 *解包元组和列表

 def add(x,y,z):
     return x+y+z
 ​
 # 解包元组
 nums = (4,6,9)
 print(add(*nums))  # 19
 ​
 # 解包列表
 nums = [4,6,9]
 print(add(*nums))  # 19
 ​
 # 解包字典
 nums = {"x":4, "y":6, "z":9}
 print(add(**nums))  # 19

下面使用 **,解包字典

 # **
 def great(name,age,phone):
     print(f"姓名:{name},年龄:{age},电话:{phone}")
 ​
 dx33661 = {"name":"dx33661","age":18,"phone":"123456789"}
 great(**dx33661)  # 姓名:dx33661,年龄:18,电话:123456789

解包赋值

顾名思义---->

**解包还可以用于变量赋值。通过 ***,可以将列表或元组中的部分元素解包为多个变量。

 a, b, c, d = (1, 2, 3, 4)
 print(a, b, c, d)  # 1 2 3 4
 ​
 # 例子
 nums1 , *nums2 , nums3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 print(nums1)
 print(nums2)
 print(nums3)
 ​

合并

主要是应用的例子

 # 用于合并两个列表
 list1 = [1, 2, 3]
 list2 = [4, 5, 6]
 list3 = [*list1, *list2]
 print(list3)  # [1, 2, 3, 4, 5, 6]
 ​
 """
 list4 = list1 + list2
 print(list4)  # [1, 2, 3, 4, 5, 6]
 """
 ​
 # 用于合并两个字典
 dict1 = {'a': 1, 'b': 2}
 dict2 = {'c': 3, 'd': 4}
 dict3 = {**dict1, **dict2}
 print(dict3)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

利用解包可以比较方便的合并多个列表或者字典


用键盘敲击出的不只是字符,更是一段段生活的剪影、一个个心底的梦想。希望我的文字能像一束光,在您阅读的瞬间,照亮某个角落,带来一丝温暖与共鸣。

BX33661

isfp 探险家

站长

不具版权性
不具时效性

文章内容不具时效性。若文章内容有错误之处,请您批评指正。


目录

欢迎来到Bpple的站点,为您导航全站动态

65 文章数
20 分类数
44 评论数
15标签数
最近评论
bpple

bpple


一切顺利

fetain

fetain


good luck

bx

bx


good luck

热门文章

Emoji收集

2024-11-01

550
Hello Halo

2024-10-30

532
本地部署LLM

2024-08-22

511
Uptime Kuma

2024-11-29

507
241

访问统计