[英]A pythonic way how to find if a value is between two values in a list
Having a sorted list and some random value, I would like to find in which range the value is. 有一个排序列表和一些随机值,我想找到值的范围。
List goes like this: [0, 5, 10, 15, 20] And value is, say 8. 列表是这样的:[0,5,10,15,20]并且值是,比方说8。
The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search . 标准方法是从开始直到我们达到比我们更大的值(如下例所示),或执行二进制搜索 。
grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
result_index += 1
print result_index
I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore. 我想知道是否有更多的pythonic方法,因为这虽然很短,看起来有点眼睛疼痛。 Thank you for your time! 感谢您的时间!
>>> import bisect
>>> grid = [0, 5, 10, 15, 20]
>>> value = 8
>>> bisect.bisect(grid, value)
2
Edit: 编辑:
for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]
if max <= value < min: #previously: if value in xrange(min, max):
return min, max
raise ValueError("value out of range")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.