Python 比较数组值的更干净的方法?
我有一个迷宫:Python 比较数组值的更干净的方法?,python,arrays,numpy,Python,Arrays,Numpy,我有一个迷宫: |||||||||||||||||||||| | || | | . | | |||||| | |||||| | |||||| | | | | |||||| || ||||| | |||| | | | | ||| ||| | | |||||||||| |||||| | | P || | |||||||||||||||||||||| 以及以下代码: imp
||||||||||||||||||||||
| || | | . |
| |||||| | |||||| |
|||||| | |
| | |||||| || |||||
| |||| | | |
| ||| ||| | |
|||||||||| |||||| |
| 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"
应该是同等的。这是纯Python。我不知道NumPy
编辑:
另一个选项(适用于所有8个方向):
那么:
print "WALL" if ("|" in theProblem[stateX+DOWN[0],stateY+DOWN[1]] + theProblem[stateX+UP[0],stateY+UP[1]] + theProblem[stateX+RIGHT[0],stateY+RIGHT[1]] + theProblem[stateX+LEFT[0],stateY+LEFT[1]]) else "GO"
好啊但是我们需要底片!实际上,从OP中的代码来看,我们只能向上、向右、向下或向左移动,不允许对角移动。所以您的两段代码都不是合适的解决方案。@PM2Ring“不允许对角移动”-哦,您可能是对的。我认为OP给出了非对角移动的例子,作为麻烦的代码,而不是所有需要的可能性。我将编辑我的答案。
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"
print "WALL" if ("|" in theProblem[stateX+DOWN[0],stateY+DOWN[1]] + theProblem[stateX+UP[0],stateY+UP[1]] + theProblem[stateX+RIGHT[0],stateY+RIGHT[1]] + theProblem[stateX+LEFT[0],stateY+LEFT[1]]) else "GO"