python使用范围_在Python中范围作为字典键

是的,只有当您将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]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值