2

所以这就是问题所在,我有一个字符“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))) 

确定单元格二维列表的邻居但它只会给我一个坐标列表,所以我仍然在后面获取值。我希望一步完成搜索和检索,因此 findNeighbors(5,5) 将返回 F,T,F,F,... 而不是 (5, 4), (5, 6), (4, 5), (4, 4)... 有快速的方法吗?解决方案可以包括一个不同于列表的结构来保存初始信息

4

1 回答 1

8

以下应该可以工作,只需对当前代码稍作修改:

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]
于 2013-04-26T21:27:10.583 回答