我尝试通过查看它们是否在给定的范围内来分散一些数字,然后根据范围分配一个数字,但是我得到的结果并不完全正确。检查数字列表是否在一定范围内?
mapp
是一个字典,它定义了范围,以及与给定范围相对应的值。
lst
的是,我要匹配这些范围,并为其分配标识符给他们
mapp = {(0,100): 1, (100,400): 2, (400,800): 3}
lst = [3.5, 5.4, 300.12, 500.78, 600.45, 900.546]
def discretize(mapping_dict, list_of_values):
print "\n"
location = []
for x in sorted(list_of_values):
for (lower_bound,upper_bound),value in mapping_dict.items():
if round(x) in range(lower_bound,upper_bound):
print round(x), "yes", value
distance = mapping_dict[(lower_bound,upper_bound)]
location.append((distance))
else:
print round(x), "no"
distance = len(mapping_dict.items())+10
location.append((distance))
return location
这是我想到的是结果号码的列表:[1, 1, 2, 3, 3, 13]
,但是这不是我所得到的。
这是实际的结果是我得到的,这是不正确的:
4.0 yes 1
4.0 no #wrong!
5.0 yes 1
5.0 no #wrong!
300.0 yes 2
300.0 no #wrong!
501.0 yes 3
501.0 no #wrong!
600.0 yes 3
600.0 no #wrong!
901.0 no #CORRECT
[1, 13, 1, 13, 2, 13, 3, 13, 3, 13, 13]
我在4.0
得到no
这是不正确的,等等,等等
问题出在哪里?
感谢
你可能只需要一次从你找到合适的组循环'break',否则'else'就一定会执行。 –
你绝对不想像你一样创造范围。你只需要使用'lower_bound <= val
acushner