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'})
但是,請注意,這會在您第一次請求時永久創建每個元素 – 并且您必須創建一個返回默認值的函數.這使得它更適用于您要更新值的情況,并且只需要將默認值作為起點.
總結
以上是生活随笔為你收集整理的python字典有什么用_在Python中使用范围作为字典键,我有什么选...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python没有错误但是不显示结果_为什
- 下一篇: python调用什么函数实现对文件内容的