检查字典键是一个整数范围 [英] Checking for a dictionary key which is a range of integers
问题描述
我正在建立制造商字典。它看起来像这样:
I'm building a dictionary of manufacturers. It would look something like this:
mfgs = {17491: 'DS', 6543: 'AC'}
在这种情况下,我需要表示一系列整数,这些整数都指向同一制造商。 (例如1-99都是由DC制造的)
In this scenario, I need to represent a range of integers that all refer to the same manufacturer. (e.g. 1 - 99 are all manufactured by DC)
我看到你可以创建一个表示范围的字典键。
I've seen that you can create a dictionary key in which a range is represented.
mfgs = {17491: 'DS', 6543: 'AC', (1,99): 'DC'}
稍后,我将从外部文件中获取一个整数。根据遇到的值,我会将相应的制造商记录到另一个文件中。
Later on, I will have an integer grabbed from an external file. Depending upon the value encountered, I will log the appropriate manufacturer into another file.
我不清楚如何检查是否存在有效的键/值对(无论是数字还是数字范围)并记录未知(如果两者都不是)在没有构建扩展的情况下发现if / then会占用字典中定义的键。
I am unclear on how to check for the presence of a valid key/value pair (whether a number or a range of numbers) and log "Unknown" if neither is found without building an expanding if/then that accounts for keys defined in the dictionary.
似乎try / except是合适的,但如果遇到21,mfg [21]会失败,它不应该。
It seems like try/except is appropriate, but if 21 is encountered, mfg[21] fails and it shouldn't.
推荐答案
您需要的不仅仅是简单的散列图(即字典)查找。哈希映射查找特定键,而不是键是否在任何现有键的范围内。
You need more than just a simple hashmap (i.e. dictionary) lookup. Hashmaps lookup particular keys, not whether a key is in range of any of the existing keys.
您有两个简单的选项。
-
如果您提前了解范围,请在查找之前将整数转换为范围:
If you know the ranges ahead of time, convert the integer into a range before looking it up:
def range_from_id(manufacturer_id):
if 1 <= manufacturer_id <= 99:
return (1, 99)
return manufacturer_id
manufacturer_id = ... from file ...
manufacturer_range = range_from_id(manufacturer_id)
manufacturer = mfgs.get(manufacturer_range, "Unknown")
如果不这样做,则在单独的字典中跟踪范围,并遍历所有可能的值:
If you don't, then keep track of the ranges in a separate dictionary, and loop through all possible values:
mfgs = {17491: 'DS', ...}
mfg_ranges = {(1, 99): 'DC', ...}
def lookup_manufacturer(manufacturer_id):
# direct look-up:
if manufacturer_id in mfgs:
return mfgs[manufacturer_id]
# range look-up:
for (start, end), mfg in mfg_ranges.items():
if start <= manufacturer_id <= end:
return mfg
return "Unknown"
如果速度是重要的是,请注意,此选项将采用 O(n)
,其中 n
是您拥有的范围数。更合适的方法是使用二进制树,如 amit在这里回答。这需要使用第三方库,如 bintrees 。
If speed is important, note that this option will take O(n)
, where n
is the number of ranges you have. A more proper way to do it would be using binary trees, as amit answered here. This would require using a 3rd party library like bintrees.
这篇关于检查字典键是一个整数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!