我会用一个函数调用来替换你的长表达式,如下所示:
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的替代方法将需要九次函数调用来计算相同的值(并且每次都评估一个非平凡的条件表达式)。