python中的索引数组(moore邻居)

python中的索引数组(moore邻居),python,numpy,Python,Numpy,主要的问题是,当I为I=2和j=1打印单元格[I-1][j]时,它应该返回1,但它表示有0。我想计算每个单元的邻域数,但这不能正常工作——但应该这样做 我有一个3 x 3的矩阵,用零添加额外的边以避免超出数组,然后在我的原始区域上有2个for循环,用值来计算邻居。但是这个计数被打破了 import numpy as np def get_generation(cells, generations): cells=np.array(cells) for k in range(generations

主要的问题是,当I
I=2
j=1
打印单元格[I-1][j]
时,它应该返回1,但它表示有0。我想计算每个单元的邻域数,但这不能正常工作——但应该这样做

我有一个3 x 3的矩阵,用零添加额外的边以避免超出数组,然后在我的原始区域上有2个for循环,用值来计算邻居。但是这个计数被打破了

import numpy as np
def get_generation(cells, generations):
cells=np.array(cells)
for k in range(generations):

    cells=np.c_[np.zeros(cells.shape[0]), cells,np.zeros(cells.shape[0])]
    cells=np.r_[[np.zeros(cells.shape[1])], cells, np.zeros(cells.shape[1])]]

    for i in range(1, cells.shape[0]-1):     #vertical
        for j in range(1, cells.shape[1]-1):     #horizontal
            neighbours=0
            neighbours+=sum(cells[i-1][j-1:j+2])
            print neighbors, cells[i-1][j-1], cells[i-1][j], cells[i-1][j+1]
            print i, j
            neighbours+=sum(cells[i+1][j-1:j+2])
            neighbours+=cells[i][j-1]
            neighbours+=cells[i][j+1]
    return cells

start = [[1,0,0],
         [0,1,1],
         [1,1,0]]

get_generation(start, 1)

您可能应该提取helper函数中邻域的总和,在该函数中,您可以使用try-except块来避免测试数组的边界:

有人这样想,也许:

import numpy as np


MOORE_OFFSETS = [(1, 1), (1, -1), (1, 0), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1)]


def get_moore_neighbors_sum(array_of_arrays, row, col):
    sum_neighbors = 0
    for neighbor in MOORE_OFFSETS:
        dr, dc = neighbor
        try:
            if row + dr >= 0 and col + dc >= 0:
                sum_neighbors += array_of_arrays[row+dr][col+dc]
        except IndexError:
            continue
    return sum_neighbors


array_of_arrays = # a sequence of sequence of your data
rows = len(array_of_arrays)
cols = len(array_of_arrays[0])

for row in range(rows):
    for col in range(cols):

        sum_neighbors = get_moore_neighbors_sum(array_of_arrays, row, col)