我有清单:
k = ["key1", "subkey2", "subsubkey3"]
Run Code Online (Sandbox Code Playgroud)
我确信这d是一个d["key1"]["subkey2"]["subsubkey3"]有效的字典.
如何将列表转换k为dict的键d以便返回d[k[0]][k[1]]...?
您可以尝试使用reduce()带operator.getitem:
>>> from operator import getitem
>>>
>>> d = {'key1': {'subkey2': {'subsubkey3': 'value'}}}
>>> k = ["key1", "subkey2", "subsubkey3"]
>>>
>>> reduce(getitem, k, d)
'value'
Run Code Online (Sandbox Code Playgroud)
在Python 3.x中,您应该使用functools.reduce().
reduce()简单地采用2参数函数并连续地将其应用于列表的元素,累积结果.还有一个可选的初始化参数,我们在这里使用它.正如文档所述,reduce()大致相当于:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
Run Code Online (Sandbox Code Playgroud)
在我们的例子中,我们正在传递一个initializer所以它不会None.因此我们拥有的是:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
Run Code Online (Sandbox Code Playgroud)
我们function在这种情况下getitem(a, b)(见上面的链接)只返回a[b].而且,我们iterable是k和我们initializer的d.所以reduce()上面的调用相当于:
accum_value = d
for x in k:
accum_value = accum_value[x]
Run Code Online (Sandbox Code Playgroud)