是的,只有当您将range列表转换为不可变的tuple列表时,您才可以这样做,这样它们就可以散列并被接受为字典的键:stealth_check = {
tuple(range(1, 6)) : 'You are about as stealthy as thunderstorm.',
编辑:实际上它在Python 3中工作,因为range是一个不可变的序列类型,并生成一个不可变的tuple,而不是像L3viathan所说的list。
但是不能用一个整数作为键来访问它们。你的最后一行行不通。
我花了一些时间创建了一个解决方案,不管值是什么(在字典中选择一个条目,只要行不被更大的范围“加权”就行)。
它调用排序键上的bisect来找到插入点,稍微修改一下,然后在字典中找到最好的值,它有O(log(N))的复杂性,这意味着它可以处理一个非常大的列表(这里可能有点太多:),但在这种情况下字典也太多了)from random import randint
import bisect
stealth_roll = randint(1, 20)
# select from a dictionary of 4 responses using one of four thresholds.
stealth_check = {
1 : 'You are about as stealthy as thunderstorm.',
6 : 'You tip-toe through the crowd of walkers, while loudly calling them names.',
11 : 'You are quiet, and deliberate, but still you smell.',
16 : 'You move like a ninja, but attracting a handful of walkers was inevitable.'
}
sorted_keys = sorted(stealth_check.keys())
insertion_point = bisect.bisect_left(sorted_keys,stealth_roll)
# adjust, as bisect returns not exactly what we want
if insertion_point==len(sorted_keys) or sorted_keys[insertion_point]!=stealth_roll:
insertion_point-=1
print(insertion_point,stealth_roll,stealth_check[sorted_keys[insertion_point]])