任何遍历嵌套字典的函数式编程方法? [英] Any Functional Programming method of traversing a nested dictionary?

查看:21
本文介绍了任何遍历嵌套字典的函数式编程方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种更好的方法来实现这一点:

d = {"a": {"b": {"c": 4}}}l = ["a", "b", "c"]对于 x 中的 l:d = d[x]打印 (d) # 4

我正在学习函数式编程,所以我只是在尝试随机出现的例子:)

解决方案

使用 <代码>reduce():

reduce(dict.__getitem__, l, d)

或者更好的是,使用 operator.getitem():

from operator import getitem减少(getitem,l,d)

演示:

<预><代码>>>>d = {"a": {"b": {"c": 4}}}>>>l = ["a", "b", "c"]>>>from 操作符 import getitem>>>减少(getitem,l,d)4

Python 3 将 reduce() 函数从内置函数移到 functools.reduce().

I am trying to find a better way to implement this:

d = {"a": {"b": {"c": 4}}} 
l = ["a", "b", "c"]
for x in l:
    d = d[x]
print (d) # 4 

I am learning functional programming so I am just trying random example that come to my head :)

解决方案

Use reduce():

reduce(dict.__getitem__, l, d)

or better still, using operator.getitem():

from operator import getitem

reduce(getitem, l, d)

Demo:

>>> d = {"a": {"b": {"c": 4}}} 
>>> l = ["a", "b", "c"]
>>> from operator import getitem
>>> reduce(getitem, l, d)
4

Python 3 moved the reduce() function out of the built-ins and into functools.reduce().

这篇关于任何遍历嵌套字典的函数式编程方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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