如何 'ignore' Python 中的索引超出范围错误

How to 'ignore' an index out of range error in Python

我的老师给我布置的任务是制作 "The Game of Life" 的 Python 版本, 所以在我让大部分代码工作之后。我被困在我怀疑是一个相当普遍的问题上:角落和边缘没有 8 个邻居。所以使用下面的代码会给我一个索引超出范围的异常:

neighbors = (a[x-1][y-1]+a[x-1][y]+a[x-1][y+1]+a[x][y-1]+a[x][y+1]
             +a[x+1][y-1]+a[x+1][y]+a[x+1][y+1])

因此,我没有使用大量 if 语句,而是想捕获超出范围的索引并传递值 0。 我将如何尝试这样做?

让你的实际电路板更宽更长 2 个单元格,用零填充边距,并使用从 1length (or width)-2 的索引。

我会编写一个辅助函数,您可以调用它 return 一个值或零(伪代码):

def getValue(x, y)
   if x < 0 or y < 0 or x > xbound or y > ybound:
       return 0
   return a[x][y]

然后你可以用不同的参数多次调用getValue

我会用单个函数调用来替换你的长表达式,如下所示:

def neighbors(a, x, y):
    total = 0
    for dx, dy in [(-1, -1), (-1, 0), (-1, 1),
                   ( 0, -1),          ( 0, 1),
                   ( 1, -1), ( 1, 0), ( 1, 1)]:
        try:
            total += a[x+dx][y+dy]
        except IndexError:
            pass
    return total

由于只有八个可能的邻居,为了获得最大速度,您可能需要考虑针对以下内容展开上面的循环:

def neighbors(a, x, y):
    xm1, xp1, ym1, yp1 = x-1, x+1, y-1, y+1
    total = 0
    try:
        total += a[xm1][ym1]
    except IndexError:
        pass
    try:
        total += a[xm1][y]
    except IndexError:
        pass
    try:
        total += a[xm1][yp1]
    except IndexError:
        pass
    try:
        total += a[x][ym1]
    except IndexError:
        pass
    try:
        total += a[x][yp1]
    except IndexError:
        pass
    try:
        total += a[xp1][ym1]
    except IndexError:
        pass
    try:
        total += a[xp1][y]
    except IndexError:
        pass
    try:
        total += a[xp1][yp1]
    except IndexError:
        pass
    return total

创建一个函数来检查每个位置的每个 x、y 的 将需要九次函数调用来计算相同的值(以及每次计算一个非平凡的条件表达式)。