【发布时间】:2020-06-18 17:45:36
【问题描述】:
假设,我有一本字典:
myList ={1:'One', 2:'two', 3:'three'}
我的代码是这样的:
if myList[4]:
last = myList[4]
else:
last = myList[3]
这会返回一个KeyError。
我知道myList.get(4,'Something')。但我正在寻找别的东西。
有没有类似的东西:
if 'KeyError' myList[4]:
last = myList[3]
else:
last = myList[4]
https://realpython.com/python-keyerror/ 这里解释了这样的方法。我试过了。但是当myList[4] 不存在时,它仍然会引发KeyError。有人可以帮我找到我在这里缺少的东西吗?
myList={1:'one', 2:'two', 3:'three'}
if 'keyError' in myList[4]:
last = myList['3']
else:
last = myList['4']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 4
try...except 方法不适合我。它使我的代码冗长而缓慢。
【问题讨论】:
-
这能回答你的问题吗? Handling key error in python
-
我要为这些 cmets 投反对票:try...except 方法不适合我。它使我的代码又长又慢和但我正在寻找别的东西。我不明白你想要什么以及你拒绝给你的 5 个答案的依据。
-
@NicolasGervais 你真的不明白,这就是为什么你没有意识到我为什么不接受这些答案。看,我标记的答案(为了您的学习目的)。顺便说一句,在 stackoverflow 上收集声誉不是我的愿景。
标签: python dictionary error-handling