递归调用python类方法 [英] call a python class method recursively

查看:66
本文介绍了递归调用python类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

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

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

I want to get the value for 'key12' so I can do this:

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

,它将返回此:

'value 13'

如果我有这样的列表:

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

如何在上述列表中递归调用 get 以返回相同的结果?

how could I call the get recursively over the above list to return the same result?

推荐答案

您可以使用

You can use 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+中,您可以使用 itertools.accumulate :

In python 3.8+ you can use the initial key in itertools.accumulate:

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

即使 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆