我有一个Python字典,每100个单位我有一个特定的值
from collections import defaultdict
nan = np.nan
points_dict_avg[100].append(10)
points_dict_avg[200].append(10)
points_dict_avg[300].append(10)
points_dict_avg[400].append(nan)
对于确定键我需要提取存储在字典中的信息
mykey = 400
如果值为nan,我希望选择上方或下方的值,并向后减去0.08到向后的值,或在向前减去0.08
#backward example
avg_dem_value = points_dict_avg[mykey][0]
while math.isnan(avg_dem_value):
new_mykey = mykey - 100
avg_dem = points_dict_avg[new_mykey][0]
avg_dem_value = avg_dem - 0.8
#forward example
points_dict_avg = defaultdict(list)
points_dict_avg[100].append(nan)
points_dict_avg[200].append(10)
points_dict_avg[300].append(10)
points_dict_avg[400].append(10)
mykey = 100
avg_dem_value = points_dict_avg[mykey][0]
while math.isnan(avg_dem_value):
new_mykey = mykey + 100
avg_dem = points_dict_avg[new_mykey][0]
avg_dem_value = avg_dem + 0.8
我希望在同一个循环中找到一个方法,同时向前和向前看,直到建立一个值,我命令避免IndexError: list index out of range
*#UPDATE: I find now this solution not very elegant with two while cycle. the first for backward and the second for forward. This is an example*
points_dict_avg = defaultdict(list)
points_dict_avg[100].append(nan)
points_dict_avg[200].append(nan)
points_dict_avg[300].append(nan)
points_dict_avg[400].append(40)
dem_value = 100
avg_dem_value = points_dict_avg[dem_value][0]
dem_value_back = dem_value
while math.isnan(avg_dem_value):
dem_value_back = dem_value_back - 100
try:
avg_dem = points_dict_avg[dem_value_back][0]
except:
avg_dem_value = nan
break
avg_dem_value = avg_dem - 0.08
dem_value_forw = dem_value
while math.isnan(avg_dem_value):
dem_value_forw = dem_value_forw + 100
try:
avg_dem = points_dict_avg[dem_value_forw][0]
except:
avg_dem_value = nan
break
avg_dem_value = avg_dem + 0.08