python IndexError:超出范围?

时间:2016-11-29 21:53:31

标签: 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 = 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)超出范围?

2 个答案:

答案 0 :(得分:0)

网格只有2个索引为0和1的元素。您可以通过评估len(Grid)来快速检查。即rn1只能有值0和1。

答案 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)

由于RandInt的包容性逻辑,-1在那里。根据文档:

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

一个次要的样式注释:如果写入此函数有一个问题,如果没有找到空格,它将进入无限循环。因此建议采用某种突破逻辑。如果您知道网格只会深入到一个元素,那么您可以执行以下操作:

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)