获取二维数组元素的方形索引

Get square shape indexes of element of 2d array

我想通过方形将元素的索引放入二维数组中

更多信息: 假设我需要获取二维数组的一个元素的索引

22 33 15

65 32 16

84 26 12

“33”的索引为 01 我想得到它的所有最近的元素,它的:22、65、32、16、15 和索引是:00、10、11、12、02

所以,我想获取类似于数组任何元素的索引

所以 x2,00 个元素是它的 3 个邻居,01 个是它的 5 个,11 个是它的 8 个邻居

还有更多: 我该如何处理超出索引值的问题?

抱歉我的英语不好

试试这个:

# example 2d arr
arr = [[22, 33, 15], [65, 32, 16], [84, 26, 12]]

# print
for row in arr:
   for col in row:
      print(col, end = " ")
   print()

def getNeighbours(x, y, arr):

    string = f'({x}, {y}): {arr[y][x]}'
    
    neighbours = []
    
    # get lengths for if check
    col_length = len(arr)
    row_length = len(arr[0])
    
    # distance options for x, y; loop
    for x_distance in [-1, 0, 1]:
        for y_distance in [-1, 0, 1]:
            # +0 and +0 == cur_position, so exclude
            # new x/y < 0 would be out of bounds, so exclude
            # new x/y == respective length would be out of bounds, so exclude
            # all else ok, hence: 'if not'
            if not ((x_distance == 0 and y_distance == 0) or \
            (y+y_distance < 0 or y+y_distance == col_length) or \
             (x+x_distance < 0 or x+x_distance == row_length)):
                neighbours.append(arr[y+y_distance][x+x_distance])
    
    return string, neighbours

# tests
result = getNeighbours(1, 0, arr)
print(result)
result = getNeighbours(1, 1, arr)
print(result)
result = getNeighbours(2, 1, arr)
print(result)

输出:

22 33 15 
65 32 16 
84 26 12 
('(1, 0): 33', [22, 65, 32, 15, 16])
('(1, 1): 32', [22, 65, 84, 33, 26, 15, 16, 12])
('(2, 1): 16', [33, 32, 26, 15, 12])

更新:如果速度是一个问题,请使用 Mechanic Pig 提供的 numpy 解决方案。

为了稍微阐明 if 逻辑,我们也可以这样写:

    # distance options for x, y; loop
    for x_distance in [-1, 0, 1]:
        for y_distance in [-1, 0, 1]:
            
            # x, y coordinates for a potential neighbour
            new_x = x + x_distance
            new_y = y + y_distance
            
            if (x_distance == 0 and y_distance == 0):
                # this will lead to the element itself, so ignore
                continue
            elif new_x < 0 or new_x == row_length:
                # new_x should fall in range(row_length), so ignore
                continue
            elif new_y < 0 or new_y == col_length:
                # same for y: new_y should fall in range(col_length), so ignore
                continue
            else:
                # any other combination of ( new_x, new_y ) is OK; append element
                neighbours.append(arr[new_y][new_x])

因为我们只是想 continueif 和 2x elif 之后,我们可以重构它并说:if not (cond1 or cond2 or cond3): neighbours.append(),如上所述。

考虑使用 numpy。

import numpy as np

arr = np.array([[22, 33, 15], [65, 32, 16], [84, 26, 12]])
row, col = 0, 1

rows, cols = np.indices(arr.shape)

mask = np.maximum(np.abs(rows - row), np.abs(cols - col)) == 1
print(rows[mask], cols[mask])
# [0 0 1 1 1] [0 2 0 1 2]
print(arr[rows[mask], cols[mask]])
# [22 15 65 32 16]

我想你稍微学习一下就可以掌握它。比循环快很多,而且不需要考虑边界问题