简体   繁体   English

在while循环中列出超出范围的索引

[英]list index out of range in while loop

I'm trying to implemnt Minesweeper game , but i'm stuck , i'm getting the list out of range error and i don't where i did wrong我正在尝试实现扫雷游戏,但我被卡住了,我得到的列表超出范围错误,我不知道我做错了什么

def Int_jeu(largeur,longueur,diff):
global n, m,T
dif = diff

n=largeur
m=longueur
T = [[0 for i in range(n)] for j in range(m)]


d=((n*m)*dif)//100
print(len(T[0]))
for i in  range(d):
    a=random.randint(0,len(T)-1)
    b=random.randint(0,len(T[0])-1)


    while (T[a][b] == "2"):

        a=random.randint(0,n-1)
        b=random.randint(0,m-1)

    T[a][b] = "2"


return(T)

this is the line where i got the error这是我得到错误的那一行

  while (T[a][b] == "2"):

i have declared the matrix T out of the int_jeu function我已经从 int_jeu 函数中声明了矩阵 T

T = []

can anyone explain me why i get the error please.任何人都可以解释我为什么我收到错误。

m is your first dimension, n is your second, but a is used to index the first dimension ( m ) while being derived from n (same for b , in reverse). m是您的第一个维度, n是您的第二个维度,但是a用于索引第一个维度 ( m ),同时从n派生而来(与b相同,相反)。

Change:改变:

    a=random.randint(0,n-1)
    b=random.randint(0,m-1)

to:到:

    a=random.randint(0,m-1)  # Or to simplify, random.randrange(m)
    b=random.randint(0,n-1)  # Or to simplify, random.randrange(n)

to fix.修理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM