如何修复Python中的“列表索引超出范围…”?

2024-03-29 12:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用Python做康威的人生游戏。我想测试这个框是否不是边框框,勾选周围的框,等等

我已经试着把这个测试放在评论中,并随机化活的邻居细胞的数量。错误消失了,但另一个问题出现了 这不是这个问题的主题。你知道吗

newArr = arr
    rows = 0
    while rows < maxRows :
        cols = 0
        while cols < maxCols :
            if cols != 0 and cols != maxCols and rows != 0 and rows != maxRows :
                checks = 0
                if arr[cols-1][rows-1] == '██' :
                    checks += 1
                if arr[cols][rows-1] == '██' :
                    checks += 1
                if arr[cols+1][rows-1] == '██' :
                    checks += 1
                if arr[cols+1][rows] == '██' :
                    checks += 1
                if arr[cols+1][rows+1] == '██' :
                    checks += 1
                if arr[cols][rows+1] == '██' :
                    checks += 1
                if arr[cols-1][rows+1] == '██' :
                    checks += 1
                if arr[cols-1][rows] == '██':
                    checks += 1

                if arr[rows][cols] == '  ' and checks == 3 :
                    newArr[rows][cols] == '██'
                if arr[rows][cols] == '██' and checks > 2 and checks < 3 :
                    newArr[rows][cols] == '██'
                else :
                    newArr[rows][cols] == '  '
            cols += 1
        rows += 1
    arr = newArr

这是错误

Traceback (most recent call last):
  File "C:/Users/acer/AppData/Local/Programs/Python/Python37/Test.py", line 55, in <module>
    if arr[cols+1][rows-1] == '██' :
IndexError: list index out of range

Tags: and游戏if错误评论rows人生cols
1条回答
网友
1楼 · 发布于 2024-03-29 12:34:15
for row in range(1, maxRows - 1):
    for col in range(1, maxCols - 1):
        aliveNeighbours = 0
        for i in range(-1, 2):
            for j in range(-1, 2):
                if arr[i + row][j + cols] = 'Your symbol' and (i != 0 or j != 0):
                    aliveNeighbours += 1
    #Then check for various conditions for conways' game of life

这将检查牢房周围是否有活着的邻居。
我们不需要边上的行和列。

>>> for i in range(-1, 2):
...     for j in range(-1, 2):
...             if i != 0 or j != 0:
...                     print(i, j)
... 
-1 -1
-1 0
-1 1
0 -1
0 1
1 -1
1 0
1 1
>>> 

这会检查每个单元格,除了它自己的单元格0,0。
如果有什么可以改进的,请发表评论。你知道吗

相关问题 更多 >