【发布时间】:2017-11-05 07:34:59
【问题描述】:
有没有更好的方法迭代地将函数列表应用到字典?这是我想做的一个例子。但这使用了递归。
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 函数并希望最小化字典副本?
【问题讨论】:
-
这不会复制任何字典;每个函数传入和传回对同一变异字典的引用。
标签: python function loops dictionary