解压缩参数列表

    技术2022-08-16  95

    解压缩参数列表

    当参数已经在列表或元组中,但需要用于单独的位置参数的函数调用需要解压时,就会发生相反的情况。例如,内置range()函数需要单独的 开始和停止参数。如果不能单独使用它们,请使用*-operator 编写函数调用, 以将参数从列表或元组中解包:

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

    字典可以用相同的方式通过**-operator 传递关键字参数 :

    def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} parrot(**d) """ 列表或者元组通过 * 解压缩参数列表 """ print(list(range(3,6))) l = [3,6] # print(list(range(l))) print(list(range(*l))) # * 将一个整体的变量l解压缩为两个变量(36) # 需要接受三个连续的参数 def fun(a,b,c): print(a,end='-') print(b,end='-') print(c,end='-') fun(1,2,3) print() l1 = [6,5,4] fun(*l1) print() ''' * 解压缩字典 {'a':1,'b':2,'c':4} ==> a,b,c 可以使用 ** 解压字典的key参数 {'a':1,'b':2,'c':4} ==> a = 1,b = 2,c = 4 ''' d = {'a':1,'b':2,'c':4} print(*d) # * 只有key值 fun(*d) # ** 有k-v对 fun(**d)
    Processed: 0.015, SQL: 9