python - How to use list to force IndexError? -


suppose have matrix list map, storing objects. per how list works, map[x-1] yields in map[eleminlist-1]. apart manually setting boundaries of x if x < 0, there other workaround?

this trying

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

example:

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

what i'm trying is, map neighboring elements each position. each positions, i'm trying add left, right, , down positions.now suppose i'm @ [1][0](f) , trying check if exists left. [1][0 - 1] point j, not i'm trying accomplish.

is you're looking do?

grid = [list('abcde'), list('fghij'), list('klmno')] print grid  neigh = [(-1,0), (0,-1), (1,0), (0,1)] nrows, ncols = 3, 5 in range(nrows):     j in range(ncols):         print 'neighbours of', grid[i][j], ':',         (dj, di) in neigh:             ni, nj = + di, j + dj             if not (0 <= ni < nrows , 0 <= nj < ncols):                 continue             print grid[ni][nj],         print  neighbours of : b f neighbours of b : c g neighbours of c : b d h neighbours of d : c e neighbours of e : d j neighbours of f : g k neighbours of g : f b h l neighbours of h : g c m neighbours of : h d j n neighbours of j : e o neighbours of k : f l neighbours of l : k g m neighbours of m : l h n neighbours of n : m o neighbours of o : n j 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -