我正在开展一个学校项目,我正在尝试浏览包含数字的列表。我正在尝试检查所有8个周围的“阻止”,但我的索引超出了范围异常
填写清单:
for i in range(0, self.sizeX):
temp = []
for j in range(0, self.sizeY):
temp.append(random.randint(0, 100))
self.map.append(temp)
检查周围的
def check(self, i, j):
count = 0
if j-1 >= 0 & self.map[i][j-1] > 50:
count += 1
if (j+1) < len(self.map[i]) & self.map[i][j+1] > 50:
count += 1
if i-1 >= 0 & self.map[i-1][j] > 50:
count += 1
if i+1 < self.sizeX & self.map[i+1][j] > 50:
count += 1
if i-1 >= 0 & j-1 >= 0 & self.map[i-1][j-1] > 50:
count += 1
if i+1 < self.sizeX & j-1 >= 0 & self.map[i+1][j-1] > 50:
count += 1
if i-1 >= 0 & j+1 < self.sizeY & self.map[i-1][j+1] > 50:
count += 1
if i+1 < self.sizeX & j+1 < self.sizeY & self.map[i+1][j+1] > 50:
count += 1
return count
它看起来像检查&gt; = 0工作的条件,但检查大小限制的一次没有 顺便说一句,我有这个确切的事情在PHP工作没有问题
答案 0 :(得分:0)
您的条件似乎是正确的,除了将&
(按位和)替换为and
(逻辑和)。
我还建议将测试作为变量拉出来;它有助于使您的代码更易于阅读。
另请注意,您使用的是列式索引,即map[x][y]
;更常见的是使用行对齐索引,即map[y][x]
。它本身并不“错误”,但可能会有点笨拙。
from random import randint
class Map:
def __init__(self, width, height):
self.width = width
self.height = height
self.map = [[randint(0, 100) for y in range(height)] for x in range(width)]
def neighbor_fn(self, i, j, fn=lambda x: x > 50):
left = i - 1
right = i + 1
above = j - 1
below = j + 1
do_left = left >= 0
do_right = right < self.width
do_above = above >= 0
do_below = below < self.height
return (
(do_left and do_above and fn(self.map[left][above]))
+ (do_above and fn(self.map[i][above]))
+ (do_right and do_above and fn(self.map[right][above]))
+ (do_left and fn(self.map[left][j]))
+ (do_right and fn(self.map[right][j]))
+ (do_left and do_below and fn(self.map[left][below]))
+ (do_below and fn(self.map[i][below]))
+ (do_right and do_below and fn(self.map[right][below]))
)