如何在try块中执行相同的代码,而不会在except子句中重复代码 [英] How can I execute same code for a condition in try block without repeating code in except clause

查看:228
本文介绍了如何在try块中执行相同的代码,而不会在except子句中重复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查列表的连续索引,如果连续的元素不相等或者列表索引超出范围,我想执行相同的代码。
这是我正在尝试

  for n in range(len(myList))
try:
如果myList [n] == myList [n + 1]:
#some代码
else:
#如果他们不相等然后做一些
#same如果引发异常,代码应该执行:index error - >我该怎么办?

有没有办法做到这一点优雅,而不必重复同样的代码在除了块不知何故?

解决方案

这样做的一个简单方法是修改if语句以检查候选元素不是最后一个,不需要一个例外条款,并保留代码。

  for n,i in enumerate(myList):
如果n + 1!= len(myList)和i == myList [n + 1]:
#some代码
else:
#如果他们不等于,然后做某事
#当最后一个元素到达时,这个块也将被显示


I am checking consecutive indices of a list and I want to execute same piece of code in case if the consecutive elements are not equal or if the list index is out of range. Here's what I'm trying

for n in range(len(myList))
    try:
         if myList[n]==myList[n+1]:
             #some code
         else:
             #if they are not equal then do something
             #same code should execute if exception raised: index error  --> how do i do this?

Is there a way to do this elegantly without having to repeat the same code in the except block somehow?

解决方案

A simple way of doing this is to just modify the if statement to check that the candidate element isn't the last one, avoiding the need for a exception clause, and keeping the code short.

    for n, i in enumerate(myList):
       if n+1 != len(myList) and i == myList[n+1]:
           #some code
       else:
           #if they are not equal then do something
           #This block will also be exicuted when last element is reached

这篇关于如何在try块中执行相同的代码,而不会在except子句中重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆