python索引器:超出范围?

python索引器:超出范围?,python,python-3.x,Python,Python 3.x,所以我使用了这段代码,显然索引超出了范围?我不明白为什么,但它给了我错误 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 = randin

所以我使用了这段代码,显然索引超出了范围?我不明白为什么,但它给了我错误

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和1。您可以通过计算len(网格)进行快速检查。也就是说,rn1只能有值0和1。

在这种情况下,您发送的“网格”在您期望的索引中没有项目

要使函数更通用,并消化传入的各种网格,可以执行以下操作:

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)
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)
由于RandInt的包容性逻辑,-1在其中。根据文件:

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

rn1
只能从0到1。您只有两个子列表。简言之,只需更改代码,使rn1被约束为0或1,您就可以开始了。