问题描述
所以,我有一个想法,我可以使用一系列数字作为字典中单个值的键.
So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.
我写了下面的代码,但我无法让它工作.甚至有可能吗?
I wrote the code bellow, but I cannot get it to work. Is it even possible?
stealth_roll = randint(1, 20)
# select from a dictionary of 4 responses using one of four ranges.
## not working.
stealth_check = {
range(1, 6) : 'You are about as stealthy as thunderstorm.',
range(6, 11) : 'You tip-toe through the crowd of walkers, while loudly calling them names.',
range(11, 16) : 'You are quiet, and deliberate, but still you smell.',
range(16, 20) : 'You move like a ninja, but attracting a handful of walkers was inevitable.'
}
print stealth_check[stealth_roll]
推荐答案
这在 Python 3 上是可能的——如果您使用 xrange
而不是 range
,则在 Python 2 上是可能的:
It is possible on Python 3 — and on Python 2 if you use xrange
instead of range
:
stealth_check = {
xrange(1, 6) : 'You are about as stealthy as thunderstorm.', #...
}
但是,您尝试使用它的方式是行不通的.您可以遍历键,如下所示:
However, the way you're trying to use it it won't work. You could iterate over the keys, like this:
for key in stealth_check:
if stealth_roll in key:
print stealth_check[key]
break
这个的性能不好 (O(n)) 但如果它是一个像你展示的那样的小字典,那就没问题了.如果您真的想这样做,我会将 dict
子类化为自动工作:
Performance of this isn't nice (O(n)) but if it's a small dictionary like you showed it's okay. If you actually want to do that, I'd subclass dict
to work like that automatically:
class RangeDict(dict):
def __getitem__(self, item):
if not isinstance(item, range): # or xrange in Python 2
for key in self:
if item in key:
return self[key]
raise KeyError(item)
else:
return super().__getitem__(item) # or super(RangeDict, self) for Python 2
stealth_check = RangeDict({range(1,6): 'thunderstorm', range(6,11): 'tip-toe'})
stealth_roll = 8
print(stealth_check[stealth_roll]) # prints 'tip-toe'
这篇关于范围作为 Python 中的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!