我使用defaultdicts来存储值的列表,其中keys
是可以观察到值的时间段。 当从感兴趣的所有时期的列表中查找时,我想找到我的默认字典中最接近的时期(注意:并非所有时期都存储在defaultdict中)。在defaultdict中查找最近的密钥
由于defaultdicts没有排序,但下面的方法不会返回正确的值。
是否有不同的方式返回defaultdicts最接近的可用键?
from collections import defaultdict
import numpy as np
def_dict = defaultdict(list)
# entries that will be stored in the defaultdict
reg_dict = {0: ["a", "b"], 2: ["c", "d"], 5: ["k", "h"], -3: ["i", "l"]}
# store items from regular dict in defaultdict
for k, v in reg_dict.items():
def_dict[k] = v
# Lookup periods
periods = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
for period in periods:
# this approach does not return the right keys as defaultdicts are not sorted
closest_key = np.abs(np.array(list(def_dict.keys())) - period).argmin()
print("period: ", period, " - looked up key: ", closest_key)
这将返回以下:
period: -1 - looked up key: 0
period: 0 - looked up key: 0
period: 1 - looked up key: 0
period: 2 - looked up key: 1
period: 3 - looked up key: 1
period: 4 - looked up key: 2
period: 5 - looked up key: 2
period: 6 - looked up key: 2
period: 7 - looked up key: 2
period: 8 - looked up key: 2
1)你并不真的需要一个'defaultdict',一个'OrderedDict'会的工作,和2你为什么不按键排序?你可以[编辑]你的帖子来显示预期的输出? –
argmin返回密钥,以便结果正确。如果你想要值,使用'min(closest_key)'。 –