这个问题的最高答案的作者使用一个lamda函数作为这个函数的参数:
>>> 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))}
像这样:
>>> print "d1 - d2:", dict_ops(d1, d2, lambda x,y: x-y)
返回:
d1 - d2: {'falsey_one': False, 'one': 1}
我试图做同样的事情,但不是作为一个函数,因为我想了解这setop部分是如何工作的。
{k:d1.get(k,k in d1 or d2[k]) for k in lambda d1,d2: set(d1) - set(d2)}
但是,此代码返回语法错误。
但这有效:
l = lambda d1,d2: set(d1) - set(d2)
{k:d1.get(k,k in d1 or d2[k]) for k in l(d1,d2)}
为什么第二个解决方案有效,但第一个无效?
如果我用这些参数调用 dict_ops 函数(d1, d2, lambda x,y: x-y)会是什么样setop(set(d1) - set(d2)子?