2016-11-29 129 views
-1

所以我使用這個小代碼片段,顯然索引超出範圍?我看不出爲什麼,但它給了我錯誤。python IndexError:超出範圍?

Grid = [[0,0,0,0],[0,0,0,0]] 

def SpawnNumber(Grid): 
    # Check is true when the random grid space is a 0 
    check = False 
    # Loop until an empty space is chosen 
    while check == False: 
     rn1 = randint(0,3) 
     rn2 = randint(0,3) 
     print(rn1) 
     print(rn2) 
     # If the space is empty, fill it 
     if Grid[rn1][rn2] == 0: 
      Grid[rn1][rn2] = 2 
      check = True 
    return(Grid) 

網格應該有兩個維度,每個維度從0-3變化,爲什麼randint(0,3)超出範圍?

+0

'rn1'應該只從0-1。你只有兩個子列表。 –

回答

0

網格只有2個索引爲0和1的元素。您可以通過評估len(Grid)進行快速檢查。即rn1只能有0和1的值。

+0

簡而言之,只需更改代碼,以便將rn1限制爲0或1,那麼您將很好。 –

0

在這種情況下,您發送的「網格」在您所期望的索引中沒有項目。

爲了讓您的功能更加全面和消化任何品種在你通過可以做類似網格:

def SpawnNumber(Grid): 
    # Check is true when the random grid space is a 0 
    check = False 
    # Loop until an empty space is chosen 
    while check == False: 
     rn1 = randint(0,len(Grid)-1) 
     rn2 = randint(0,len(Grid[rn1])-1) 
     print(rn1) 
     print(rn2) 
     # If the space is empty, fill it 
     if Grid[rn1][rn2] == 0: 
      Grid[rn1][rn2] = 2 
      check = True 
    return(Grid) 

在那裏-1是因爲RandInt的包容性的邏輯。每文檔:

random.randint(a, b) 
    Return a random integer N such that a <= N <= b 

A小調風格注:書面這個功能有一個問題是,如果沒有空的空間發現它會進入一個無限循環。因此建議採用某種突破邏輯。如果你知道網格只能走一個元素深,你可以做這樣的事情:

def SpawnNumber(Grid): 
    # Check is true when the random grid space is a 0 
    check = False 
    # Check if there are any open spots 
    for row in Grid: 
     if all(row): 
      check = True 
    # Loop until an empty space is chosen 
    while check == False: 
     rn1 = randint(0,len(Grid)-1) 
     rn2 = randint(0,len(Grid[rn1])-1) 
     print(rn1) 
     print(rn2) 
     # If the space is empty, fill it 
     if Grid[rn1][rn2] == 0: 
      Grid[rn1][rn2] = 2 
      check = True 
    return(Grid) 
相關問題