Python dict:如何将键映射到值,其中键是一个范围?

Pyd*_*man 0 python dictionary list map range

我有一个值列表:

[0,1.51,2.01,2.51,3.01,5.01,6.01,7.01,8.01,9.01,10.01]

第二个值列表:

[.15,.22,.3,.37,.4,.5,.6,.7,.8,.9,1]

我的程序的粗略逻辑是,如果某个变量的值落在第一个列表中的两个值之间,则将另一个变量的值设置为第二个列表中的相应项,即

if 0 < x < 1.51:
    y = 0.15
elif 1.51 < x < 2.01:
    y = .22
and so on
Run Code Online (Sandbox Code Playgroud)

显然我可以扩展if/elif/else流程以涵盖每个案例,但(i)这不是很好,(ii)它不可持续(iii)我希望能够将此应用于任何两个列表,而不是要求知道其中包含的任何值.

在Python中实现这一目标的最佳方法是什么?

非常感谢

Jon*_*nts 7

看看bisect模块 - http://docs.python.org/2/library/bisect.html

以及百分比 - >等级的例子:

>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
        i = bisect(breakpoints, score)
        return grades[i]

>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
Run Code Online (Sandbox Code Playgroud)