简体   繁体   English

一种pythonic方法,用于查找值是否在列表中的两个值之间

[英]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: 编辑:

bisect — Array bisection algorithm bisect - 数组二分算法

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.

相关问题 查找列表中两个元素之间关系的最pythonic方法 - Most pythonic way to find relation between two elements in a list 在 2D 列表中查找值的 Pythonic 方法? - Pythonic way to find value in 2D list? python:在值列表和模型对象列表(即模型对象值)之间以pythonic方式查找差异 - python: find diff in pythonic way between list of values and list of model object i.e with models objects values 从另一个列表中存在的两个列表中查找2个项目的Python方法 - Pythonic way to find 2 items from two lists existing in a another list 在列表中查找具有值的最小字典键的 Pythonic 方法? - Pythonic way to find a minimum dictionary key with value in a list? 比较两个词典列表中的价值的Pythonic方法 - Pythonic Way to Compare Values in Two Lists of Dictionaries 如何查看列表中的值是否介于另一个列表中的两个值之间 - how to see if there is a value in a list that is between two values from another list 从列表中创建字典的 Pythonic 方法,其中键是在另一个列表中找到的元素,值是键之间的元素 - Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys 查找列表中对象最少出现的Python方法 - Pythonic way to find fewest occurrences of object in list Pythonic将两个列表“合并”到元组列表的方法 - Pythonic way to “merge” two lists to a list of tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM