Python,在二维列表中查找邻居

时间:2013-04-26 21:21:16

标签: python list data-structures matrix

所以这就是问题,我有一个2-D字符列表'T'和'F',给定坐标我需要得到它的所有邻居。我有这个:

from itertools import product, starmap
x, y = (5, 5)
cells = starmap(lambda a, b: (x + a, y + b), product((0, -1, +1), (0, -1, +1))) 

来自determining neighbors of cell two dimensional list但它只会给我一个协调员列表,所以我仍然会获取后面的值。我希望一步完成搜索和检索,所以findNeighbors(5,5)将返回F,T,F,F,...而不是(5,4),(5,6),(4, 5),(4,4)......有这么快的方法吗? solutin可以包括除列表之外的结构以保存初始信息

1 个答案:

答案 0 :(得分:7)

以下内容应该有效,只需对当前代码稍作调整即可:

from itertools import product, starmap, islice

def findNeighbors(grid, x, y):
    xi = (0, -1, 1) if 0 < x < len(grid) - 1 else ((0, -1) if x > 0 else (0, 1))
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    return islice(starmap((lambda a, b: grid[x + a][y + b]), product(xi, yi)), 1, None)

例如:

>>> grid = [[ 0,  1,  2,  3],
...         [ 4,  5,  6,  7],
...         [ 8,  9, 10, 11],
...         [12, 13, 14, 15]]
>>> list(findNeighbors(grid, 2, 1))   # find neighbors of 9
[8, 10, 5, 4, 6, 13, 12, 14]
>>> list(findNeighbors(grid, 3, 3))   # find neighbors of 15
[14, 11, 10]

为了清楚起见,这里有一些没有所有itertools魔术的等效代码:

def findNeighbors(grid, x, y):
    if 0 < x < len(grid) - 1:
        xi = (0, -1, 1)   # this isn't first or last row, so we can look above and below
    elif x > 0:
        xi = (0, -1)      # this is the last row, so we can only look above
    else:
        xi = (0, 1)       # this is the first row, so we can only look below
    # the following line accomplishes the same thing as the above code but for columns
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    for a in xi:
        for b in yi:
            if a == b == 0:  # this value is skipped using islice in the original code
                continue
            yield grid[x + a][y + b]