python字典有什么用_在Python中使用范围作为字典键,我有什么选...

我不确定这是否是你想要的,但dict.get可能是答案:

>>> ub_tries = 20

>>> tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}

>>> tries_dict.get(1, 'next')

'first'

>>> tries_dict.get(4, 'next')

'fourth'

>>> tries_dict.get(5, 'next')

'next'

>>> tries_dict.get(20, 'next')

'last'

>>> tries_dict.get(21, 'next')

'next'

当然,你可以用各种不同的方式将它包装在一个函数中.例如:

def name_try(try_number, ub_tries):

tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}

return tries_dict.get(try_number, 'next')

无论如何,dict.get(key,default = None)就像dict [key],除了如果key不是成员,而不是引发KeyError,它返回默认值.

至于你的建议:

using a range as a key??

当然,你可以这样做(如果你使用的是Python 2而不是3,请使用xrange作为范围),但它会如何帮助?

d = { range(1, 5): '???',

range(5, ub_tries): 'next',

range(ub_tries, ub_tries + 1): 'last' }

这完全合法 – 但d [6]会引发KeyError,因为6与range(5,ub_tries)不同.

如果你想要这个,你可以像这样构建一个RangeDictionary:

class RangeDictionary(dict):

def __getitem__(self, key):

for r in self.keys():

if key in r:

return super().__getitem__(r)

return super().__getitem__(key)

但这远远超出了“初学者的Python”,即使对于这种非常低效,不完整和不健壮的实现,所以我不建议这样做.

finding a way to generate a list with values between 4 and ub_tries and using such list as a key

你的意思是这样的?

>>> ub_tries = 8

>>> tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}

>>> tries_dict.update({i: 'next' for i in range(5, ub_tries)})

>>> tries_dict

{1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'next', 6: 'next', 7: 'next', 8: 'last'}

>>> tries_dict[6]

'next'

这可行,但它可能不是一个好的解决方案.

最后,您可以使用defaultdict,它允许您将默认值烘焙到字典中,而不是将其作为每个调用的一部分传递:

>>> from collections import defaultdict

>>> tries_dict = defaultdict(lambda: 'next',

... {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'})

>>> tries_dict

defaultdict( at 0x10272fef0>, {8: 'last', 1: 'first', 2: 'second', 3: 'third', 4: 'fourth'})

>>> tries_dict[5]

'next'

>>> tries_dict

defaultdict( at 0x10272fef0>, {1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'next', 8: 'last'})

但是,请注意,这会在您第一次请求时永久创建每个元素 – 并且您必须创建一个返回默认值的函数.这使得它更适用于您要更新值的情况,并且只需要将默认值作为起点.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值