查找值在范围列表中的位置的 Pythonic 方法 [英] Pythonic way of finding where a value is in a list of ranges
问题描述
我有一个开始和结束值字典的列表:
I have a list of start and end value dicts:
a = [
{'start': 1, 'end': 3},
{'start': 5, 'end': 6},
{'start': 8, 'end': 10}
]
列表保证有序,没有任何重叠.给定一个值,我需要找到它在列表中的位置.如果它在定义的范围之一内,我需要取回该值.否则,我需要按顺序获得下一个开始"值.例如,给定 b = 2
,我会取回 2
值,因为它在第一个范围内.但是,给定值 b = 7
我会返回 8
因为它是从 7 开始的下一个范围的起始值.
The list is guaranteed to be in order, and not have any overlap. Given a value, I need to find where in the list it falls. If it is in one of the defined ranges, I need to get the value back. Otherwise, I need the next 'start' value in sequence. e.g., given b = 2
, I would get back the value 2
because it is in the first range. However, given the value b = 7
I would get back 8
as it is the start value for the next range in sequence from 7.
我已经写了一些代码来做到这一点:
I have written some code to do this:
def where_in_range(v, val_ranges):
# Check if v comes before all ranges
if v < val_ranges[0]['start']:
return val_ranges[0]['start']
# Check if v is within one of the ranges
for r in val_ranges:
if v >= r['start'] and v <= r['end']:
return v
# Check if v is between ranges
for i in range(0, len(val_ranges)-1):
if v > val_ranges[i]['end'] and v < val_ranges[i+1]['start']:
return val_ranges[i+1]['start']
return None
但它似乎非常非pythonic.我愿意使用一个轻量级的包,但是像 Pandas 一样重的东西已经出来了,因为它被嵌入到了 django 应用程序中.关于如何使这更加 Pythonic 的任何想法?
But it seems quite non-pythonic. I am willing to use a lightweight package, but something as heavy as pandas is out, as this is being embedded in a django application. Any thoughts on how to make this more pythonic?
推荐答案
只需单独检查每个范围.范围内的值会自动处理,任何范围前的值也是如此.
Just check each range individually. Inter-range values are handled automatically, as are any pre-range values.
def where_in_range(v, val_ranges):
for d in val_ranges:
if v < d['start']:
return d['start']
elif v < d['end']:
return v
这篇关于查找值在范围列表中的位置的 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!