将函数应用于参数列表的排列
Apply function to permutations of lists of arguments
我需要获取 n 个参数和 n 个值列表的函数,并将该函数应用于每个可能的参数排列。我查看了 itertools,没有一个功能是完全正确的。以下是我的尝试。有人可以解释我做错了什么吗?谢谢
def CrossReference(f, *args):
result = []
def inner(g, *argsinner):
rest = argsinner[1:]
a = argsinner[0]
if type(a) is not list:
a = [a]
for x in a:
h = partial(g, x)
if len(rest) > 0:
inner(h, rest)
else:
result.append(h())
inner(f, args)
return result
这是我的示例测试和错误:
def sums(x,y,z):
return x+y+z
CrossReference(sums, [1,2,3], 4, [5,6,7])
回溯(最近调用最后):文件“”,第 1 行,
在文件“”中,第 13 行,
在交叉引用文件“”,第 12 行,在内部
TypeError: sums() 正好需要 3 个参数(给定 1 个)
问题在于您调用 inner
函数的方式。您将函数头定义为:
def inner(g, *argsinner):
但是你这样调用你的函数:
inner(f, args)
并且:
inner(h, rest)
这意味着您最终将得到一个包含参数元组的元组(单元组?)。您可以将函数定义更改为:
def inner(g, argsinner):
或将您的呼叫更改为:
inner(h, *rest)
def sums(x,y=0,z=0):
return x+y+z
def apply(fn,*args):
for a in args:
try:
yield fn(*a)
except TypeError:
try:
yield fn(**a)
except TypeError:
yield fn(a)
print list(apply(sums,[1,2,3], 4, [5,6,7]))
这是您可以做到的一种方式(虽然不是唯一的方式)
我需要获取 n 个参数和 n 个值列表的函数,并将该函数应用于每个可能的参数排列。我查看了 itertools,没有一个功能是完全正确的。以下是我的尝试。有人可以解释我做错了什么吗?谢谢
def CrossReference(f, *args):
result = []
def inner(g, *argsinner):
rest = argsinner[1:]
a = argsinner[0]
if type(a) is not list:
a = [a]
for x in a:
h = partial(g, x)
if len(rest) > 0:
inner(h, rest)
else:
result.append(h())
inner(f, args)
return result
这是我的示例测试和错误:
def sums(x,y,z):
return x+y+z
CrossReference(sums, [1,2,3], 4, [5,6,7])
回溯(最近调用最后):文件“”,第 1 行, 在文件“”中,第 13 行, 在交叉引用文件“”,第 12 行,在内部 TypeError: sums() 正好需要 3 个参数(给定 1 个)
问题在于您调用 inner
函数的方式。您将函数头定义为:
def inner(g, *argsinner):
但是你这样调用你的函数:
inner(f, args)
并且:
inner(h, rest)
这意味着您最终将得到一个包含参数元组的元组(单元组?)。您可以将函数定义更改为:
def inner(g, argsinner):
或将您的呼叫更改为:
inner(h, *rest)
def sums(x,y=0,z=0):
return x+y+z
def apply(fn,*args):
for a in args:
try:
yield fn(*a)
except TypeError:
try:
yield fn(**a)
except TypeError:
yield fn(a)
print list(apply(sums,[1,2,3], 4, [5,6,7]))
这是您可以做到的一种方式(虽然不是唯一的方式)