如何使用list强制IndexError?
How to use list to force IndexError?
假设我有一个类似于列表 map
的矩阵,我在其中存储了一些对象。现在根据列表的工作方式,map[x-1]
产生 map[elemInList-1]
。除了像 if 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
我想做的是从每个位置映射相邻元素。因此,对于每个位置,我尝试添加左、右、上和下 positions.Now 假设我在 [1][0]
(F) 并尝试检查其左侧是否存在任何内容。 [1][0 - 1] 会指向 j,这不是我想要完成的。
这是您想要做的吗?
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
假设我有一个类似于列表 map
的矩阵,我在其中存储了一些对象。现在根据列表的工作方式,map[x-1]
产生 map[elemInList-1]
。除了像 if 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
我想做的是从每个位置映射相邻元素。因此,对于每个位置,我尝试添加左、右、上和下 positions.Now 假设我在 [1][0]
(F) 并尝试检查其左侧是否存在任何内容。 [1][0 - 1] 会指向 j,这不是我想要完成的。
这是您想要做的吗?
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