python - 函数参数中的元组解包

标签 python python-3.x tuples

在下面的函数中,args[i] 应该通过前面的 * 解压到函数 func 的参数中,但是传入的是一个列表。我错过了什么?

def mymap(func, *seq):
    args = list(zip(seq))
    ret = []
    for i in range(len(args)):
        print(type(args[i]))
        ret.append( func(*args[i]) )
    return ret

f = lambda x: x+2

mymap(f, [1,2,3])

最佳答案

* 打包在函数定义中并在函数调用中解包。

定义一个新函数:

def func1(*args):
    print(args)

这个包:

>>> func1(1, 2)
(1, 2)

具有两个参数的函数

def func2(a, b):
    print(a)
    print(b)

可以使用*通过序列调用:

>>> func2(*[1, 2])
1
2

关于python - 函数参数中的元组解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446291/

相关文章:

python - 在 Python 中保存 VTK 中的数据数组

where 子句中的 Swift 元组

list - 无法理解 Haskell 中的元组递归是如何工作的

python - 计算 DataFrame 列中的 NaN 窗口(及其大小)

python - Popen/Wait - 等待永远不会结束

Scala - 在编译时强制执行 Vector 的大小

python - 标识符中的Unicode下标和上标,为什么Python认为XU == Xᵘ == Xᵤ?

python - 在 Python 脚本中保护密码

python - 使用 python 2.7 : sh: -c: line 0: syntax error near unexpected token `('

python异步图像下载(多个url)