首页 > 解决方案 > 递归调用python类方法

问题描述

我有一本看起来像这样的字典:

d ={'key1':{'key2':{'key11':{'key12':'value 13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}

我想获得'key12'的值,所以我可以这样做:

d.get('key1').get('key2').get('key11').get('key12')

它会返回这个:

'value 13'

如果我有这样的清单:

['key1', 'key2', 'key11', 'key12']

我怎么能get递归地调用上面的列表来返回相同的结果?

标签: pythonclassrecursionmethods

解决方案


您可以使用functools.reduce

>>> from functools import reduce
>>> keys = ['key1', 'key2', 'key11', 'key12']
>>> reduce(dict.get, keys, d)
#or, reduce(lambda x,y:x.get(y), keys, d)
'value 13'

在 python 3.8+ 中,您可以使用以下initialitertools.accumulate

>>> from itertools import accumulate
>>> list(accumulate(keys, dict.get, initial=d))[-1]
'value 13'

我还是更喜欢functools.reduce,即使Guido doesn't


推荐阅读