[英]How can I use lambda as function parameter?
The author of the top answer of this question uses a lamda function as parameter for this function: 这个问题的最佳答案的作者使用 lamda function 作为这个 function 的参数:
>>> d1 = {'one':1, 'both':3, 'falsey_one':False, 'falsey_both':None}
>>> d2 = {'two':2, 'both':30, 'falsey_two':None, 'falsey_both':False}
def dict_ops(d1, d2, setop):
... """Apply set operation `setop` to dictionaries d1 and d2
...
... Note: In cases where values are present in both d1 and d2, the value from
... d1 will be used.
... """
... return {k:d1.get(k,k in d1 or d2[k]) for k in setop(set(d1), set(d2))}
Like this:像这样:
>>> print "d1 - d2:", dict_ops(d1, d2, lambda x,y: x-y)
Which returns:哪个返回:
d1 - d2: {'falsey_one': False, 'one': 1}
I tried to do the same thing but not as a function, because I want to understand how the setop
part works.我尝试做同样的事情,但不是作为 function,因为我想了解
setop
部分是如何工作的。
{k:d1.get(k,k in d1 or d2[k]) for k in lambda d1,d2: set(d1) - set(d2)}
However this code returns a syntax error.但是,此代码返回语法错误。
But this works:但这有效:
l = lambda d1,d2: set(d1) - set(d2)
{k:d1.get(k,k in d1 or d2[k]) for k in l(d1,d2)}
Why does the second solution work, but the first one dont?为什么第二种解决方案有效,但第一种无效?
If I call the dict_ops function with these parameters (d1, d2, lambda x,y: xy)
how does setop(set(d1) - set(d2)
look like?如果我用这些参数调用 dict_ops function
(d1, d2, lambda x,y: xy)
setop(set(d1) - set(d2)
看起来像什么?
If you do an exact substitution, it will work.如果您进行精确替换,它将起作用。 You have:
你有:
{... for k in setop(set(d1), set(d2))}
The value passed in for setop
is:为
setop
传入的值是:
lambda x,y: x-y
A direct substitution of setop
is: setop
的直接替代是:
{... for k in (lambda x,y: x-y)(set(d1), set(d2))|
which will work.这将工作。
For the second version, you have:对于第二个版本,您有:
{... for k in l(d1,d2)}
where l
is:其中
l
是:
lambda d1,d2: set(d1) - set(d2)
A direct substitution here produces:此处的直接替换会产生:
{... for k in (lambda d1,d2: set(d1) - set(d2))(d1,d2)}
which will also work.这也将工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.