如何使用list强制IndexError?

时间:2016-01-16 19:16:09

标签: python list nodes

假设我有一个类似列表map的矩阵,我存储了一些对象。现在,根据列表的工作原理,map[x-1]会产生map[elemInList-1]。除了像x < 0那样手动设置x的边界外,还有其他解决方法吗?

这就是我的尝试

for x in range(row):
    for y in range(col):
        try:
            print "trying left", map[x][y - 1]
            map[x][y].neighbors.append(map[x][y - 1])
        except IndexError:
            pass

示例:

a b c d e
f g h i j
k l m n o

我要做的是,映射每个位置的相邻元素。因此,对于每个位置,我正在尝试添加左,右,上和下位置。现在假设我在[1][0](F)并尝试检查其左侧是否存在任何位置。 [1] [0 - 1]会指向j,这不是我想要完成的。

1 个答案:

答案 0 :(得分:1)

这是你想要做的吗?

grid = [list('abcde'), list('fghij'), list('klmno')]
print grid

neigh = [(-1,0), (0,-1), (1,0), (0,1)]
nrows, ncols = 3, 5
for i in range(nrows):
    for j in range(ncols):
        print 'neighbours of', grid[i][j], ':',
        for (dj, di) in neigh:
            ni, nj = i + di, j + dj
            if not (0 <= ni < nrows and 0 <= nj < ncols):
                continue
            print grid[ni][nj],
        print

neighbours of a : b f
neighbours of b : a c g
neighbours of c : b d h
neighbours of d : c e i
neighbours of e : d j
neighbours of f : a g k
neighbours of g : f b h l
neighbours of h : g c i m
neighbours of i : h d j n
neighbours of j : i e o
neighbours of k : f l
neighbours of l : k g m
neighbours of m : l h n
neighbours of n : m i o
neighbours of o : n j