有沒有更好的方法來迭代將函數列表應用於字典?這是我想要做的一個例子。但是這使用遞歸。在Python中有沒有更好的方法來將一個函數列表應用到字典中
def func1(h: dict):
h['foo']=10
return(h)
def func2(h: dict):
h['bar']=100
return(h)
def func3(h: dict):
h['baz']=h['foo']+h['bar']
return(h)
func3(func2(func1({'firstElement':'good'})))
可生產預期輸出:
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
欲提供用作陣列和產生相同的輸出。下面是我曾嘗試和作品:
def recApply(flist, h=None):
"""
Helper Apply the list of functions iteratively over the dictionary passed
:obj: function list each will be applied to the dictionary sequentially.
"""
#if no dictionary passed, then set the dictionary.
if(h == None):
h = {}
#iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
for f in flist:
h = f(h)
return(h)
flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})
這將產生所需的輸出:
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
有沒有辦法做到這一點,是更具可讀性,刪除recApply功能,並希望最大限度地減少字典副本?
這不會複製任何字典;對同一個突變字典的引用被傳入並從每個函數返回。 – chepner