我不确定这是否是你想要的,但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'})
但是,请注意,这会在您第一次请求时永久创建每个元素 – 并且您必须创建一个返回默认值的函数.这使得它更适用于您要更新值的情况,并且只需要将默认值作为起点.