Python 2:如何将元组中的参数传递给函数?

时间:2018-02-15 15:23:53

标签: python python-2.7 functional-programming python-2.x

我想将一个参数元组args(由于某些其他函数而在元组长度上变化)传递给函数,该函数可以正常工作

def myf(x1,x2,x3,....)
    return something involving x1,x2....

args = (y1,y2,.....)

call myf with args as myf(y1,y2,....)

你是如何实现这一目标的?在我的实际问题中,我正在使用sympy函数myf实际上是reshape而变量参数列表args是通过获取某些nd-的形状而生成的元组数组,说A,所以args = A.shape。最后,我想根据B的形状重塑另一个数组A。最小的例子是

from sympy import *
A = Array(symbols('a:2:3:4:2'),(2,3,4,2))
B = Array(symbols('b:8:3:2'),(8,3,2))
args = A.shape
print args
print B.reshape(2,3,4,2) # reshape(2,3,4,2) is the correct way to call it
print B.reshape(args) # This is naturally wrong since reshape((2,3,4,2)) is not the correct way to call reshape

2 个答案:

答案 0 :(得分:5)

使用参数解包:

def myf(x1,x2,x3):
    return x1 + x2 + x3

args = (1, 2, 3)

myf(*args)  # 6

答案 1 :(得分:1)

你需要解压缩元组:

B.reshape(*args)