Python 2:如何将元组中的参数传递给函数?
Python 2: how to pass arguments in tuple to a function?
我想将参数元组 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
是通过获取某些 n-d- 的形状生成的元组数组,说 A
,所以 args = A.shape
。最后我想根据 A
的形状重塑另一个数组 B
。一个最小的例子
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
使用参数解包:
def myf(x1,x2,x3):
return x1 + x2 + x3
args = (1, 2, 3)
myf(*args) # 6
您需要解压元组:
B.reshape(*args)
我想将参数元组 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
是通过获取某些 n-d- 的形状生成的元组数组,说 A
,所以 args = A.shape
。最后我想根据 A
的形状重塑另一个数组 B
。一个最小的例子
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
使用参数解包:
def myf(x1,x2,x3):
return x1 + x2 + x3
args = (1, 2, 3)
myf(*args) # 6
您需要解压元组:
B.reshape(*args)