简体   繁体   English

为什么我的try-except块卡在了循环中?

[英]why is my try- except block stuck in the loop?

I am trying to catch an Index out of range error with the following try and except block. 我正在尝试使用以下try和except块捕获索引超出范围错误。

def getStepList(r, h, d):
    x = len(r)-1
    y = len(h)-1
    list = []
    while True:
        try:
            if x == 0 and y == 0: 
                break
            elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1] and r[x-1] == h[y-1]:
                x = x - 1
                y = y - 1
            elif y >= 1 and d[x][y] == d[x][y-1]+1:
                #insertion
                x = x
                y = y - 1
                list.append(h[y])
                print('insertion')

            elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1]+1:
                #substitution
                x = x - 1
                y = y - 1
                list.append(r[x])
                print('substitution')

            else:
                #deletion
                x = x - 1
                y = y
                list.append(r[x])
                print('deletion')

        except IndexError:
            print('index error')

    return list[::-1]

but it gets stuck in a infinite loop. 但是它陷入了无限循环。 I want it to ignore it and proceed appending the next instances. 我希望它忽略它并继续添加下一个实例。 (For reference its a piece of code that uses a metric of another function to determine which words were inserted, substituted or deleted at each operation). (作为参考,它是一段代码,它使用另一个函数的度量来确定每个操作中插入,替换或删除的单词)。

I feel like I should know this, but in all honesty I am stuck. 我觉得我应该知道这一点,但是老实说,我被困住了。

Don't do a while True. 暂时不要做。 Change your while condition to: 将您的while条件更改为:

while(not (x == 0 and y == 0)):

Inside your exception also add a break 在您的异常中也添加一个中断

except IndexError:
     print('index error')
     break

You could also add some checks to see what the specific Index Error might be: 您还可以添加一些检查以查看特定的索引错误可能是什么:

d_len = len(d)
r_len = len(r)
h_len = len(h)
d_x_of_y_len = len(d[x][y])
if(x > d_len):
    print("x is too big")
if(y > d_x_of_y_len):
    print("y is too big")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM