我有一个迷宫:
||||||||||||||||||||||
| || | | . |
| |||||| | |||||| |
|||||| | |
| | |||||| || |||||
| |||| | | |
| ||| ||| | |
|||||||||| |||||| |
| P || |
||||||||||||||||||||||
以及以下代码:
import numpy
import copy
import collections
UP = [0,1]
DOWN = [0,-1]
LEFT = [-1,0]
RIGHT = [1,0]
theProblem = numpy.empty((rows,cols), dtype=object)
## code to generate the below matrix ##
[['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|'
'|' '|' '|' '|']
['|' ' ' '|' '|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' ' ' '|' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' '|' '|' '|' '|' '|' '|' ' ' '|' ' ' '|' '|' '|' '|'
'|' '|' ' ' '|']
['|' '|' '|' '|' '|' '|' ' ' ' ' ' ' ' ' ' ' 'P' ' ' ' ' '|' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' '|' ' ' '|' '|' '|' '|' '|' '|' ' ' '|' '|' ' ' '|'
'|' '|' '|' '|']
['|' ' ' '|' '|' '|' '|' ' ' '|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|'
' ' ' ' ' ' '|']
['|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' '|' '|' ' ' '|' '|' '|' ' ' ' '
' ' '|' ' ' '|']
['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' ' ' ' ' ' ' ' ' '|' '|' '|' '|'
'|' '|' ' ' '|']
['|' '.' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|' '|' ' ' ' ' ' ' ' ' ' '
' ' ' ' ' ' '|']
['|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|' '|'
'|' '|' '|' '|']]
#######################################################################
# stateX = location of P[0] #
# stateY = location of P[1] #
print "WALL" if theProblem[stateX+DOWN[0],stateY+DOWN[1]] == '|' else "GO"
是否有更简洁的方法来进行最后一行比较?我对 numpy 还很陌生,但似乎必须有一种更聪明的方法来比较周围的单元格,而无需明确执行以下操作:
print "WALL" if theProblem[stateX+DOWN[0],stateY+DOWN[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+UP[0],stateY+UP[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+LEFT[0],stateY+LEFT[1]] == '|' else "GO"
print "WALL" if theProblem[stateX+RIGHT[0],stateY+RIGHT[1]] == '|' else "GO"
最佳答案
# if diagonal movements are accepted
neighbours = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1))
# if diagonal movements are NOT accepted
neighbours = ((0, -1), (-1, 0), (1, 0), (0, 1))
for neighbour in neighbours:
if theProblem[stateX + neighbour[0], stateY + neighbour[1]] == '|':
print "WALL"
else:
print "GO"
应该是等价的。这是纯Python。我不知道 NumPy。
编辑: 另一种选择(适用于所有 8 个方向):
for x in range(-1,2):
for y in range(-1,2):
if (x, y) != (0, 0):
if theProblem[stateX + x, stateY + y] == '|':
print "WALL"
else:
print "GO"
关于python - 比较数组值的更简洁的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621596/