字典中的数据插值 python 3

interpolation of data in dictionary python 3

我有一个 python 程序,它使用嵌套字典执行计算。问题是,如果有人输入的值不在其中一个词典中,它将不起作用。我可以强制用户从值中进行选择,但我宁愿执行插值以获得 'expected' 值。不过,我不知道如何解压这些词典、对它们进行排序以及执行插值。

如有任何帮助,我们将不胜感激。我的代码如下。

像这样的词典:

from decimal import *
pga_values = {
    "tee": {
        100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12,       240:3.25, 260:3.45, 280:3.65,
    300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17,
    480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82
},
"fairway": {
    5:2.10,10:2.18,20:2.40,30:2.52,40:2.60,50:2.66,60:2.70,70:2.72,80:2.75,

ETC...(编辑简明扼要)

lie_types = set(pga_values.keys())
user_preshot_lie = input("What was your pre-shot lie type?")
user_preshot_distance_to_hole = Decimal(input('How far away from the hole   were you before your shot?'))
user_postshot_lie = input("What was your post-shot lie type?")
user_postshot_distance_to_hole = Decimal(input('How far away from the hole were you?'))
assert user_preshot_lie in lie_types
assert user_postshot_lie in lie_types

preshot_pga_tour_shots_to_hole_out = pga_values[user_preshot_lie][user_preshot_distance_to_hole]
postshot_pga_tour_shots_to_hole_out = pga_values[user_postshot_lie][user_postshot_distance_to_hole]

user_strokes_gained = Decimal((preshot_pga_tour_shots_to_hole_out -     postshot_pga_tour_shots_to_hole_out)-1)

print(user_strokes_gained)

例如,为了稍微隔离问题:

tee = {
    100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12, 240:3.25, 260:3.45, 280:3.65,
300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17,
480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82
}

你可以……:

import bisect
teekeys = sorted(tee)

def lookup(aval):
    where = bisect.bisect_left(teekeys, aval)
    lo = teekeys[where-1]
    hi = teekeys[where]
    if lo==hi: return tee[lo]
    delta = float(aval-lo)/(hi-lo)
    return delta*tee[hi] + (1-delta)*tee[lo]

例如:

print(lookup(110))
2.955
print(lookup(530))
4.595

不确定如果值为 <min(tee)>max(tee) 时您想做什么 -- 在这种异常情况下是否可以引发异常?