在查找表中查找范围内的值 [英] Find value within a range in lookup table

查看:107
本文介绍了在查找表中查找范围内的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最简单的问题要实现,但到目前为止,我还没办法解决Python中的解决方案.

I have the simplest problem to implement, but so far I have not been able to get my head around a solution in Python.

我建立了一个与此表相似的表:

I have built a table that looks similar to this one:

501 - ASIA
1262 - EUROPE
3389 - LATAM
5409 - US

我将测试某个值以查看它是否在这些范围内,即389 -> ASIA, 1300 -> LATAM, 5400 -> US.大于5409的值不应返回查找值.

I will test a certain value to see if it falls within these ranges, 389 -> ASIA, 1300 -> LATAM, 5400 -> US. A value greater than 5409 should not return a lookup value.

我通常有一对一的匹配,并且会为查询实现字典.

I normally have a one to one match, and would implement a dictionary for the lookup.

但是在这种情况下,我必须考虑这些范围,而我并没有看到解决问题的方法.

But in this case I have to consider these ranges, and I am not seeing my way out of the problem.

也许没有提供完整的解决方案,您能否提供一些意见以帮助我朝正确的方向看?

Maybe without providing the whole solution, could you provide some comments that would help me look in the right direction?

它与电子表格中的vlookup非常相似.

It is very similar to a vlookup in a spreadsheet.

我会把我的Python知识描述为介于基础知识和中级知识之间.

I would describe my Python knowledge as somewhere in between basic to intermediate.

推荐答案

您可以使用bisect模块.而不是线性搜索,它将使用二进制搜索,希望它会更快:

You could use the bisect module. Instead of linear search, that would use binary search, which would hopefully be faster:

import bisect

places = [
    (501, 'ASIA'),
    (1262, 'EUROPE'),
    (3389, 'LATAM'),
    (5409, 'US'),
]
places.sort() # list must be sorted

for to_find in (389, 1300, 5400):
    pos = bisect.bisect_right(places, (to_find,))
    print '%s -> %s' % (to_find, places[pos])

将打印:

389 -> (501, 'ASIA')
1300 -> (3389, 'LATAM')
5400 -> (5409, 'US')

这篇关于在查找表中查找范围内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆