You can imagine a field like this:
0 0 S 0 0 0 0 S 0
Since your condition is one and large, this square can be represented not as a two-dimensional, but as a one-dimensional array: 0 0 S 0 0 0 0 S 0
. If the map is a two-dimensional map
array and the x, y coordinates are the center of the square to be checked, then you can get a one-dimensional cut operation. In this case, the field is 5x5 and check the point right in the center.
import itertools my_map = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] y = 2 x = 2 current = my_map[x][y] my_map[x][y] = 'CURRENT' arr = itertools.chain(*[row[max(x - 1, 0): x + 2] for row in map[max(y - 1, 0): y + 2]]) print(1 in arr) my_map[x][y] = current
An extra array can be not initialized. Replacing the current cell is necessary to exclude the cell from consideration without complicated formulas or conditions.
Here several operators were used:
1) The slice operator ":" (slice). Example of use:
l = ['a', 'b', 'c', 'd', 'e', 'f'] print(l[2:4]) >>> ['c', 'd']
2) Unpacking operator of the collection "*" ( doc ):
l = ['a', 'b', 'c', 'd', 'e', 'f'] print(*l) abcdef
The essence of the operator is that the array l
turned into 6 different values ​​(there was 1 list - it became 6 elements without a list).
3) The chain
function from the itertools
module - sticks arrays to one ( doc ):
l = itertools.chain(['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'i', 'o']) print(list(l)) >>> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'o']
4) Operator in, which checks whether the item is in the collection or not ( doc ):
l = ['a', 'b', 'c', 'd', 'e', 'f'] print('a' in l) print('z' in l) >>> True >>> False
numpy.array
, then the test is reduced to the presence of'S'
in the selected area of ​​a two-dimensional array. - mkkikarray[nrow-1 : nrow+2, ncol-1 : ncol+2]
, wherenrow, ncol
is the desired cell. Slices, of course, receive through lambda. - mkkik