有没有办法防止索引包装?

时间:2015-03-21 17:33:28

标签: python matrix

我有以下内容:

# Possible neighbors as tuples
UP = (-1,0)
DOWN = (1,0)
LEFT = (0,-1)
RIGHT = (0,1)
POTENTIAL_NEIGHBORS = (UP, DOWN, LEFT, RIGHT)

def LocateNeighbors(self):
        print '\nWorking on: {}:{}'.format(self.index,self.value)
        for n in POTENTIAL_NEIGHBORS:
            try:
                if theBoard[self.index[0]+n[0]][self.index[1]+n[1]]:
                    print "Adding neighbor: " + theBoard[self.index[0]+n[0]][self.index[1]+n[1]]
                    self.neighbors.append(n)
            except IndexError:
                print 'failed on: {}'.format(n)

..其中self是游戏板中的一个单元格,例如:

      A      B      C      D      E      F
1 | {66} | {76} | {28} | {66} | {11} | {09}
-------------------------------------------
2 | {31} | {39} | {50} | {08} | {33} | {14}
-------------------------------------------
3 | {80} | {76} | {39} | {59} | {02} | {48}
-------------------------------------------
4 | {50} | {73} | {43} | {03} | {13} | {03}
-------------------------------------------
5 | {99} | {45} | {72} | {87} | {49} | {04}
-------------------------------------------
6 | {80} | {63} | {92} | {28} | {61} | {53}
-------------------------------------------

但是,这是我正在检查的第一个单元格的输出(0,0):

Working on: (0, 0):66
Adding neighbor: 80
Adding neighbor: 31
Adding neighbor: 09
Adding neighbor: 76

基本上,如果索引(我认为是)无效,它就会回滚到列表的末尾。有没有办法防止或至少检测到这种行为?或者,或许更优雅的方式来做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用范围检查功能:

def check(n):
    if n<0:
        raise IndexError(n)
    return n

def LocateNeighbors(self):
    print '\nWorking on: {}:{}'.format(self.index,self.value)
    for n in POTENTIAL_NEIGHBORS:
        try:
            if theBoard[check(self.index[0]+n[0])][check(self.index[1]+n[1])]:
                print "Adding neighbor: " + theBoard[self.index[0]+n[0]][self.index[1]+n[1]]
                self.neighbors.append(n)
        except IndexError:
            print 'failed on: {}'.format(n)

答案 1 :(得分:2)

按照以下行添加支票:

if (0 <= (self.index[0] + n[0]) < num_cols) and 
   (0 <= (self.index[1] + n[1]) < num_rows):
    # Do stuff here

当你在董事会的对面边缘时,你应该避免IndexError

编辑:

丹尼尔的回答更像是Pythonic,我想。它遵循EAFP原则。