python - 发生异常时继续循环
问题描述
我希望循环继续进行,即使在第一次迭代时产生异常。这个怎么做?
mydict = {}
wl = ["test", "test1", "test2"]
try:
for i in wl:
a = mydict['sdf']
print(i)
except:
# I want the loop to continue and print all elements of list, instead of exiting it after exception
# exception will occur because mydict doesn't have 'sdf' key
pass
解决方案
您可以使用dict.get()
. None
如果密钥不存在,它将返回。您还可以在中指定默认值dict.get(key, default_value)
for i in wl:
a = mydict.get('sdf')
print(i)
推荐阅读
- python - [Python]-无法通过使用 input() 函数为其赋值来确定变量类型,为什么?
- c# - 在导出到 xls 之前隐藏列值
- python-3.x - 用索引值替换布尔数据框中的所有 True
- python - 是否有与 Ada “然后”和“或其他”等价的 Python?(懒惰的评价)
- sql - 如何在具有多个条件的特定列中执行计算
- android - 如何将日期存储为 SharedPreference?
- python - 如何根据其他列的值在 Pandas 中包含移动平均线
- python - 如何解决在scrapy中忽略响应429
- ios - UIScrollView 里面的 UITableView 不会触发 ScrollToRow
- ios - 我应该在 ReactiveObjc 中使用 @strongify(self) 之前检查弱自我的存在吗?