我有以下设置:一个函数返回一个具有N个相同大小的时间线(100k点)的字典。字典返回如下:
timelines = dict()
timelines["Name1"] = dict()
timelines["Name1"]["Name2"] = dict()
timelines["Name1"]["Name3"] = dict()
timelines["Name1"]["Name2"]["a"] = # List of 100k points
timelines["Name1"]["Name2"]["b"] = # List of 100k points
timelines["Name1"]["Name2"]["c"] = # List of 100k points
timelines["Name1"]["Name3"]["b"] = # List of 100k points
timelines["Name1"]["Name2"]["c"] = # List of 100k points
timelines["Name1"]["a"] = # List of 100k points
timelines["Name1"]["b"] = # List of 100k points
timelines["Name2"] # and so on.
如您所知,时间线(点列表)并不总是存储在同一级别。有时我可以用1个键访问它,有时用2,有时用5。
这些键将给我标绘图的标签,而且是必要的。我的计划是向plot函数传递一组键。
例子:
T = ("Name1", "Name2", "b")
# Will allow me to access the timeline:
timelines["Name1"]["Name2"]["b"]
# by doing:
timelines[T[0]][T[1]][T[2]]
在上面的示例中,我自己编写了字典路径(
[T[0]][T[1]][T[2]]
),但是如何使用大小未知的元组T访问正确的时间线?如何将元组解包到字典路径中?Thanks :)
最佳答案
I would actually do it like this, this will be the fastest method more than likely
from functools import reduce
from operator import getitem
path = ['Name1', 'Name2', 'a']
reduce(getitem, path, dictionary)
Lambda
调用会变得昂贵,尤其是随着数据的增长,更不用说getitem
比这里列出的任何其他方法都快,因为它是在C
中实现的