我想能够咖喱merge_with
:
merge_with
如我所料
>>> from cytoolz import curry, merge_with
>>> d1 = {"a" : 1, "b" : 2}
>>> d2 = {"a" : 2, "b" : 3}
>>> merge_with(sum, d1, d2)
{'a': 3, 'b': 5}
在一个简单的函数上,curry
按我的预期工作:
>>> def f(a, b):
... return a * b
...
>>> curry(f)(2)(3)
6
但我无法“手动”制作merge_with
的咖喱版本:
>>> curry(merge_with)(sum)(d1, d2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> curry(merge_with)(sum)(d1)(d2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
预咖喱版本的作品:
>>> from cytoolz.curried import merge_with as cmerge
>>> cmerge(sum)(d1, d2)
{'a': 3, 'b': 5}
我的错在哪里?你知道吗
这是因为
merge_with
将dicts
作为位置参数:因此
f
是唯一的强制参数,对于空的*args
,您将得到一个空字典:所以:
相当于
您必须显式地定义helper
可以根据需要使用:
或:
两者都可以
以及:
相关问题 更多 >
编程相关推荐