簡體   English   中英

Python:列表索引超出范圍,不知道為什么

[英]Python: List index out of range, don't know why

我正在嘗試遍歷矩陣,並檢查接觸當前單元格的值為1的單元格數量。我遇到了異常,我不確定為什么。

for x in range(0,ROWS):
    for y in range(0,COLS):

        #get neighbors
        neighbors = []
        if x!=0 & y!=COLS:
            neighbors.append([x-1,y+1])
        if y!=COLS:
            neighbors.append([x,y+1])
        if x!=ROWS & y!=COLS:
            neighbors.append([x+1,y+1])
        if x!=0:
            neighbors.append([x-1,y])
        if x!=ROWS:
            neighbors.append([x+1,y])
        if x!=0 & y!=0:
            neighbors.append([x-1,y-1])
        if y!=0:
            neighbors.append([x,y-1])
        if x!=ROWS & y!=0:
            neighbors.append([x+1,y-1])

        #determine # of living neighbors
        alive = []
        for i in neighbors:
            if matrix[i[0]][i[1]] == 1:
                alive.append(i)

我遇到了錯誤

IndexError:列表索引超出范圍

if matrix[i[0]][i[1]] == 1:在此行if matrix[i[0]][i[1]] == 1:

為什么這超出范圍,我應該如何解決?

編輯:我認為我找到了它

在進一步檢查您的代碼后,我發現您正在使用if x!=0 & y!=0 這是按位AND而不是邏輯AND,因此不會給您想要的結果。 使用and而不是&查看問題是否消失。

我將對此稍作重構,以使其更易於閱讀。

for loc_x in range(ROWS):
    for loc_y in range(COLS): # btw shouldn't ROWS/COLS be flipped?
                              # if your matrix isn't square this could be why
        x_values = [loc_x]
        if loc_x < ROWS: x_values.append(loc_x+1)
        if loc_x > 0: x_values.append(loc_x-1)
        y_values = [loc_y]
        if loc_y < COLS: y_values.append(loc_y+1)
        if loc_y > 0: y_values.append(loc_y-1)
        neighbors = [(x,y) for x in x_values for y in y_values if (x,y) != (loc_x,loc_y)]

        alive = [matrix[n[0]][n[1]] for n in neighbors if matrix[n[0]][n[1]]==1]

嘗試用您的代碼運行它,看看它是否不能解決問題。 如果沒有,您可能需要進一步測試。 例如,將alive定義包裝在try/except標記中,以提供更好的回溯。

try:
    alive = ...
except IndexError:
    print("Location: {},{}\nneighbors: {}\nROWS:{}\nCOLS:{}".format(x_loc,y_loc, neighbors,ROWS,COLS))
    raise

順便說一句,我已經通過創建保存鏈接信息的對象並從上到下從左到右,並讓每個對象檢查字段的右側和下方來解決此問題。 例如:

class Field(object):
    def __init__(self,x,y,value):
        self.x = x
        self.y = y
        self.value = value
        self.neighbors = neighbors

class Matrix(list):
    def __init__(self,size):
        self.ROWS,self.COLS = map(int,size.lower().split("x"))
        for y in range(ROWS):
            self.append([Field(x,y,random.randint(0,1)) for x in range(COLS)])
        self.plot()
    def plot(self):
        for row in self:
            for col in row:
                try:
                    self[row][col].neighbors.append(self[row+1][col])
                    self[row+1][col].neighbors.append(self[row][col])
                except IndexError: pass
                try:
                    self[row][col].neighbors.append(self[row][col+1])
                    self[row][col+1].neighbors.append(self[row][col])
                except IndexError: pass

當然,這不會處理對角線。 我很確定您可以弄清楚如何管理這些!

問題是您正在使用& 這是按位與,而不是邏輯與。 在Python中,您只需使用and 例如:

if x!=0 and y!=COLS:
    neighbors.append([x-1,y+1])

但是,使用按位AND導致問題的真正原因是操作順序-它具有更高的優先級!

>>> 1 != 2 & 3 != 3
True
>>> (1 != 2) & (3 != 3)
False
>>> 1 != (2 & 3) != 3
True

因此,即使您的邏輯看起來正確,操作順序也意味着您代碼的實際行為與您的預期有很大不同。

代碼的另一個問題是,您要檢查xy是否等於ROWSCOLS ,而不是它們是否等於ROWS-1COLS-1 ,這是真實的邊界條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM