我想过滤一个特定级别的嵌套字典,例如:
d = {'fruit': {'sweet': {'green': 'apple', 'red': 'tomato'}, 'bitter': {'green': 'cucumber'}}}
我想写一个函数filter_at_level( d, 2, lambda r: r == 'green' )
,只返回以下内容而不修改原始数据:
{'fruit': {'sweet': {'green': 'apple'}, 'bitter': {'green': 'cucumber'}}}
我应该避免递归吗?它可以在没有递归的情况下有效地编写吗?
答案 0 :(得分:1)
from itertools import ifilter
def f(d, func, l):
if l == 0:
return {k: d[k] for k in ifilter(func, d)}
return {k: f(v, func, l - 1) for k, v in d.iteritems()}
d = {'fruit': {'sweet': {'green': 'apple', 'red': 'tomato'}, 'bitter': {'green': 'cucumber'}}}
print f(d, lambda k: k == 'green', 2)
或者如果你不想要空元素:
from itertools import ifilter
def f(d, func, l):
if l == 0:
return {k: d[k] for k in ifilter(func, d)}
tmp = {k: f(v, func, l - 1) for k, v in d.iteritems()}
return {k: v for k, v in tmp.iteritems() if v}
d = {'fruit': {'sweet': {'green': 'apple', 'red': 'tomato'}, 'bitter': {'green': 'cucumber'}, 'x': {'a': 'z'}}}
print f(d, lambda k: k == 'green', 2)