我使用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)'。 –