简体   繁体   English

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

[英]Python, finding neighbors in a 2-d list

So here's the issue, I have a 2-d list of characters 'T' and 'F', and given coordinates I need to get all of its neighbors. 所以这就是问题,我有一个2-D字符列表'T'和'F',给定坐标我需要得到它的所有邻居。 I have this: 我有这个:

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))) 

from determining neighbors of cell two dimensional list But it will only give me a list of coordinantes, so i still fetch the values afterwords. 确定单元格二维列表的邻居但它只会给我一个协调列表,所以我仍然获取后面的值。 I'd like the search and retrieval done in one step, so findNeighbors(5,5) would return F,T,F,F,... instead of (5, 4), (5, 6), (4, 5), (4, 4)... Is there a fast way of doing this? 我希望一步完成搜索和检索,所以findNeighbors(5,5)将返回F,T,F,F,...而不是(5,4),(5,6),(4, 5),(4、4)...是否有快速的方法? The solutin can include a structure other than a list to hold the initial information Solutin可以包含除列表以外的其他结构以保存初始信息

The following should work, with just a minor adaptation to the current code: 以下应该可以工作,只需稍微调整当前代码:

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)

For example: 例如:

>>> 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]

For the sake of clarity, here is some equivalent code without all of the itertools magic: 为了清楚起见,下面是一些等效的代码,没有所有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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM