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

标签 python list data-structures matrix

所以这就是问题所在,我有一个字符“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)... 有快速的方法吗?解决方案可以包含除列表以外的结构来保存初始信息

最佳答案

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

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]

关于Python,在二维列表中寻找邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16245407/

相关文章:

Python - 基准测试磁盘 - 在文件中准确写入 x 字节

Python setuptools 入口点和子应用程序作为子进程

c# - 在 x 个较小列表之间平均拆分项目列表

java - 我应该使用什么数据结构来实现下一次剩余到期时间最少的调度

performance - 有效的数据结构来保存带有通配符的字符串

python - 一旦发生,就在 Pandas 中填写一个值

python - Pandas :如何过滤数据帧中至少出现 n 次的重复项目的数据帧

c# - 将数据集转换为列表

c# - 有没有办法在 Visual Studio 中自动生成 equals 和 hashcode 方法

c++ - 哈希键和值