传递函数以不同数量的变量运行 [英] pass function to function with different number of variables
本文介绍了传递函数以不同数量的变量运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def foo(A,B)
。 现在我有另一个函数 bar(func)
,其中 func
是一个只有一个变量的函数。我想在 foo
中传入 func
,但第二个变量 B
总是固定为300.我该怎么做?解析方案
使用 lambda
:
bar(lambda x:foo(x,300))
$基本上,
func = lambda x:x * x
或多或少相当于:
def func(x):
return x * x
所以在这种情况下,我们使用或多或少等价的东西:
def new_func (x):
return foo(x,300)
然后我们通过等价 new_func
至栏
。
Suppose I have a function def foo(A, B)
.
Now I have another function bar(func)
, where func
is a function that takes only one variable. I want to pass in foo
as func
, but with the second variable B
always fixed to 300. How can I do that?
解决方案 You use lambda
:
bar(lambda x: foo(x,300))
basically,
func = lambda x: x*x
is more or less equivalent to:
def func(x):
return x*x
So in this case, we use something that's more or less equivalent to:
def new_func(x):
return foo(x,300)
and then we pass the equivalent of new_func
to bar
.
这篇关于传递函数以不同数量的变量运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文