如何处理for循环中的错误(python)并继续执行

secatt

我试图让我的脚本仍无法执行动作2“打印(list1 [3])”,而跳过动作1“打印(list1 [9])”。如果我的问题不够清楚,我会积极地争取尽我所能来解释这个问题。我是初学者。

list1 = ['a','b','c','d','f']

try:
  for i in list1:
    #action 1
    print (list1[9])
    #action 2
    print (list1[3])
    break
except:
  pass
Chems Eddine

尝试这种更清洁的方式

  l = ['a','b','c','d','f']

  # execute the function in try-except
  def try_to_do(fun, index):
     try:
        fun(l[index])
     except:
        pass

  for j in l:
     try_to_do(print, 11)
     try_to_do(print, 1)

  print('Done')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章