如何使用列表强制索引器?

2024-10-03 09:08:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个类似于listmap的矩阵,在这里我存储了一些对象。现在根据列表的工作方式,map[x-1]map[elemInList-1]中产生。除了像ifx < 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,这不是我想要实现的。你知道吗


Tags: 对象方法inmap列表for方式range
1条回答
网友
1楼 · 发布于 2024-10-03 09:08:44

这就是你想做的吗?你知道吗

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

相关问题 更多 >