字典 Python 3 中的数据插值



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

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

像这样的词典:

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,

等。。。(编辑简明扼要)

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),您想做什么 - 在这种异常情况下引发异常可以吗?

最新更新