📜  Python中的打包和解包参数

📅  最后修改于: 2022-05-13 01:55:25.553000             🧑  作者: Mango

Python中的打包和解包参数

我们使用两个运算符*(用于元组)和 **(用于字典)。

背景
考虑一种情况,我们有一个接收四个参数的函数。我们想要调用这个函数,我们有一个大小为 4 的列表,其中包含函数的所有参数。如果我们只是将一个列表传递给函数,则调用不起作用。

Python3
# A Python program to demonstrate need
# of packing and unpacking
 
# A sample function that takes 4 arguments
# and prints them.
def fun(a, b, c, d):
    print(a, b, c, d)
 
# Driver Code
my_list = [1, 2, 3, 4]
 
# This doesn't work
fun(my_list)


Python3
# A sample function that takes 4 arguments
# and prints the,
def fun(a, b, c, d):
    print(a, b, c, d)
 
# Driver Code
my_list = [1, 2, 3, 4]
 
# Unpacking list into four arguments
fun(*my_list)


Python3
# Error when len(args) != no of actual arguments
# required by the function
 
args = [0, 1, 4, 9]
 
 
def func(a, b, c):
    return a + b + c
 
 
# calling function with unpacking args
func(*args)


Python3
>>>
>>> range(3, 6)  # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)  # call with arguments unpacked from a list
[3, 4, 5]


Python3
# A Python program to demonstrate use
# of packing
 
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
    return sum(args)
 
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))


Python3
# A Python program to demonstrate both packing and
# unpacking.
 
# A sample python function that takes three arguments
# and prints them
def fun1(a, b, c):
    print(a, b, c)
 
# Another sample function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed into tuple *args.
def fun2(*args):
 
    # Convert args tuple to a list so we can modify it
    args = list(args)
 
    # Modifying args
    args[0] = 'Geeksforgeeks'
    args[1] = 'awesome'
 
    # UNPACKING args and calling fun1()
    fun1(*args)
 
# Driver code
fun2('Hello', 'beautiful', 'world!')


Python3
# A sample program to demonstrate unpacking of
# dictionary items using **
def fun(a, b, c):
    print(a, b, c)
 
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(**d)


Python3
# A Python program to demonstrate packing of
# dictionary items using **
def fun(**kwargs):
 
    # kwargs is a dict
    print(type(kwargs))
 
    # Printing dictionary items
    for key in kwargs:
        print("%s = %s" % (key, kwargs[key]))
 
# Driver code
fun(name="geeks", ID="101", language="Python")


输出 :

TypeError: fun() takes exactly 4 arguments (1 given)


开箱
我们可以使用*解包列表,以便它的所有元素都可以作为不同的参数传递。

Python3

# A sample function that takes 4 arguments
# and prints the,
def fun(a, b, c, d):
    print(a, b, c, d)
 
# Driver Code
my_list = [1, 2, 3, 4]
 
# Unpacking list into four arguments
fun(*my_list)

输出 :

(1, 2, 3, 4)

我们需要记住,没有。参数的数量必须与我们为参数解包的列表的长度相同。

Python3

# Error when len(args) != no of actual arguments
# required by the function
 
args = [0, 1, 4, 9]
 
 
def func(a, b, c):
    return a + b + c
 
 
# calling function with unpacking args
func(*args)

输出:

Traceback (most recent call last):
  File "/home/592a8d2a568a0c12061950aa99d6dec3.py", line 10, in 
    func(*args)
TypeError: func() takes 3 positional arguments but 4 were given

作为另一个示例,考虑需要单独的开始和停止参数的内置 range()函数。如果它们不能单独使用,请使用 *-运算符编写函数调用,以将参数从列表或元组中解包出来:

Python3

>>>
>>> range(3, 6)  # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)  # call with arguments unpacked from a list
[3, 4, 5]

包装
当我们不知道需要将多少个参数传递给一个Python函数时,我们可以使用 Packing 将所有参数打包到一个元组中。

Python3

# A Python program to demonstrate use
# of packing
 
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
    return sum(args)
 
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))

输出:

15
30

上述函数mySum() 执行“打包”以将此方法调用接收到的所有参数打包到一个变量中。一旦我们有了这个“打包”变量,我们就可以用它来做我们用普通元组做的事情。 args[0] 和 args[1] 会分别给你第一个和第二个参数。由于我们的元组是不可变的,您可以将 args 元组转换为列表,以便您还可以修改、删除和重新排列 i 中的项目。

打包和拆包
下面是一个显示打包和拆包的示例。

Python3

# A Python program to demonstrate both packing and
# unpacking.
 
# A sample python function that takes three arguments
# and prints them
def fun1(a, b, c):
    print(a, b, c)
 
# Another sample function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed into tuple *args.
def fun2(*args):
 
    # Convert args tuple to a list so we can modify it
    args = list(args)
 
    # Modifying args
    args[0] = 'Geeksforgeeks'
    args[1] = 'awesome'
 
    # UNPACKING args and calling fun1()
    fun1(*args)
 
# Driver code
fun2('Hello', 'beautiful', 'world!')

输出:

(Geeksforgeeks, awesome, world!)

** 用于字典

Python3

# A sample program to demonstrate unpacking of
# dictionary items using **
def fun(a, b, c):
    print(a, b, c)
 
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(**d)

输出:

2 4 10

这里 ** 解压了与它一起使用的字典,并将字典中的项目作为关键字参数传递给函数。所以写“fun(1, **d)”就相当于写“fun(1, b=4, c=10)”。

Python3

# A Python program to demonstrate packing of
# dictionary items using **
def fun(**kwargs):
 
    # kwargs is a dict
    print(type(kwargs))
 
    # Printing dictionary items
    for key in kwargs:
        print("%s = %s" % (key, kwargs[key]))
 
# Driver code
fun(name="geeks", ID="101", language="Python")
输出

name = geeks
ID = 101
language = Python

应用和要点

  1. 在套接字编程中用于向服务器发送大量请求。
  2. 在 Django 框架中用于将变量参数发送到视图函数。
  3. 有些包装函数需要我们传入可变参数。
  4. 参数的修改变得容易,但同时验证不正确,因此必须小心使用它们。