python - 递归调用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
递归地调用上面的列表来返回相同的结果?
解决方案
您可以使用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+ 中,您可以使用以下initial
键itertools.accumulate
:
>>> from itertools import accumulate
>>> list(accumulate(keys, dict.get, initial=d))[-1]
'value 13'
我还是更喜欢functools.reduce
,即使Guido doesn't
推荐阅读
- android - 如何使用 Thread 调用 getDataFromApi() 函数
- c++ - 关闭 QDialog 窗口是否会删除其动态添加的 UI 元素?
- python - 字数列表无法重命名列名
- php - 我需要重定向 http://站点名称和 www.sitename.com,但它重定向到 https://www
- swift - 快速换色显示不同颜色
- angular - Angular 6 StaticInjectorError(平台:核心)没有提供者
- vue.js - 计算属性“对话框”已分配给但它没有设置器
- angularjs - 重新调整angularjs材料设计数据表列宽的大小
- python - 为什么 python socket.recvfrom 得到的字节流与 WireShark 爬取的字节流不同?
- node.js - 如何重复(添加循环)具有角度内容的html元素