更清洁的比较数组值的方法?

时间:2015-02-20 04:23:23

标签: python arrays numpy

我有一个迷宫:

||||||||||||||||||||||
| ||        | |    . |
|    |||||| | |||||| |
||||||        |      |
|    | |||||| || |||||
| |||| |         |   |
|        ||| |||   | |
||||||||||    |||||| |
|  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"

2 个答案:

答案 0 :(得分:3)

# 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"

答案 1 :(得分:0)

怎么样:

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"
相关问题