检查数字在哪个范围内
问题描述:
我需要找出一个数字在哪个范围内,在本例中为 value
.除了这个,我找不到任何其他方法来将 i
设置为我需要的:
I need to find which range a number, in this case value
, is within. I cannot find any other way to set i
to what I need other than this:
if value < -64:
i = 0
elif value < -32:
i = 1
elif value < -16:
i = 2
elif value < -8:
i = 3
elif value < -4:
i = 4
elif value < -2:
i = 5
elif value < -1:
i = 6
elif value < -0.5:
i = 7
elif value < 0:
i = 8
elif value < 0.5:
i = 9
elif value < 1:
i = 10
elif value < 2:
i = 11
elif value < 4:
i = 12
elif value < 8:
i = 13
elif value < 16:
i = 14
elif value < 32:
i = 15
elif value < 64:
i = 16
else:
i = 17
这是糟糕的代码,我讨厌它.有什么办法可以做这样的事情吗?
This is terrible code and I hate it. Is there any way I can do something like this?
ranges = [-64, -32, -16 ... 32, 64]
i = find_which_range(value, ranges)
谢谢!
答
使用 bisect:
import bisect
ranges = [-64, -32, -16, -8, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 8, 16, 32, 64]
print(bisect.bisect(ranges, -65))
# 0
print(bisect.bisect(ranges, -64))
# 1
print(bisect.bisect(ranges, 63))
#16
print(bisect.bisect(ranges, 64))
# 17
bisect.bisect(l, value)
返回必须在 l
中插入 value
的索引,这样所有的值左边小于 value
.搜索大列表也会很快,因为它使用二分算法.
bisect.bisect(l, value)
returns the index at which value
would have to be inserted in l
, such that all values to the left are less than value
. It will also be fast to search a large list, as it uses a bisection algorithm.