我不确定这是否是你想要的,但^{}可能是答案:>>> 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]类似,只是如果