[英]Currying merge_with in python toolz
我希望能夠咖喱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
但是我無法“手動”制作curry版本的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
的位置參數:
merge_with(func, *dicts, **kwargs)
所以f
是唯一的強制性參數,對於空*args
您將得到一個空字典:
>>> curry(merge_with)(sum) # same as merge_with(sum)
{}
所以:
curry(f)(2)(3)
相當於
>>> {}(2)(3)
Traceback (most recent call last):
...
TypeError: 'dict' object is not callable
您必須明確並定義助手
def merge_with_(f):
def _(*dicts, **kwargs):
return merge_with(f, *dicts, **kwargs)
return _
可以根據需要使用:
>>> merge_with_(sum)(d1, d2)
{'a': 3, 'b': 5}
要么:
def merge_with_(f, d1, d2, *args, **kwargs):
return merge_with(f, d1, d2, *args, **kwargs)
兩者都可以
>>> curry(merge_with_)(sum)(d1, d2)
{'a': 3, 'b': 5}
和:
>>> curry(merge_with_)(sum)(d1)(d2)
{'a': 3, 'b': 5}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.