字典并集以及星号*的解压(unpack)作用

字典的并集

首先看实现字典并集的例子:

def merge(d1, d2):
    return {**d1, **d2}

 星号*的使用

当参数已经在列表或元组中,但需要为需要独立位置参数的函数调用解包时,则会出现相反的情况。例如,内置的range()函数需要单独的start和stop参数。如果它们不能单独使用,用*-操作符编写函数调用,将参数从列表或元组中解包出来

range(3, 6)
#输出:[3, 4, 5]

args = [3, 6]
range(*args)
#输出:[3, 4, 5]

字典中的解压使用**

def parrot(voltage, state='a stiff', action='voom'):
    print("-- This parrot wouldn't"+ action)
    print( "if you put"+ voltage +"volts through it.") 
    print("E's"+ state+"!")

d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)

#输出 
#-- This parrot wouldn'tVOOM
#if you putfour millionvolts through it.
#E'sbleedin' demised!
原文地址:https://www.cnblogs.com/yzh1008/p/12455598.html