data = {"c":{"files":"s","d":{"files":["nothing"]}}}
positions = ["c","d","files"]
我怎样才能获得我在名单中的位置"职位"?我需要从列表"位置"像这样的东西:
data["c"]["d"]["files"]
我还需要处理该位置的列表。我已经尝试了一些东西,但我无法以我想要的方式使用该列表。
def goto(data,positions):
temp = data
for i in positions:
temp = temp[i]
有没有很酷的方法呢?
答案 0 :(得分:3)
这是reduce
的工作!
reduce(lambda a,b: a[b], positions, data)
如果您使用的是Python 3,则需要导入reduce
,如下所示:
from functools import reduce
在Python 2中,它是一个内置函数,因此不需要导入。