范围作为Python中的字典键 [英] Range as dictionary key in Python
本文介绍了范围作为Python中的字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我有一个想法,我可以使用一系列数字作为字典中单个值的键。
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]
推荐答案
感谢大家的回应。我一直在偷走,我想出了一个很适合我目的的解决方案。它最类似于@PaulCornelius的建议。
Thank you everyone for your responses. I kept hacking away, and I came up with a solution that will suit my purposes quite well. It is most similar to the suggestions of @PaulCornelius.
stealth_roll = randint(1, 20)
# select from a dictionary of 4 responses using one of four ranges.
# only one resolution can be True. # True can be a key value.
def check(i, a, b): # check if i is in the range. # return True or False
if i in range(a, b):
return True
else:
return False
### can assign returned object as dictionary key! # assign key as True or False.
stealth_check = {
check(stealth_roll, 1, 6) :
'You are about as stealthy as a thunderstorm.',
check(stealth_roll, 6, 11) :
'You tip-toe through the crowd of walkers, while loudly calling them names.',
check(stealth_roll, 11, 16) :
'You are quiet, and deliberate, but still you smell.',
check(stealth_roll, 15, 21) :
'You move like a ninja, but attracting a handful of walkers was inevitable.'
}
print stealth_check[True] # print the dictionary value that is True.
这篇关于范围作为Python中的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文