python:类型错误和索引错误(2.7.6)

时间:2016-08-25 02:22:49

标签: python list indexing typeerror

我对python很新,我在2.7.6上遇到问题3.4.4上没有问题

代码:

def answer(population, x, y, strength):

# make sure Z is infectable
if population[x][y] > strength:
    return population
else:
    population[x][y] = -1

# get array dimentions
rows = len(population)
cols = len(population[0])

# declare checking array
toCheck = []
toCheck.append([x,y])

# loop 4 way check
while(1):
    #store and pop current element
    i = toCheck[0][0]
    j = toCheck[0][1]
    toCheck.pop(0)

    # left
    if j != 0:
        if population[i][j-1] <= strength and population[i][j-1] != -1:
            population[i][j-1] = -1
            toCheck.append([i,j-1])

    # top
    if i != 0:
        if population[i-1][j] < strength and population[i-1][j] != -1:
            population[i-1][j] = -1
            toCheck.append([i-1,j])

    # right 
    if j != cols-1:
        if population[i][j+1] > strength and population[i][j+1] != -1:
            population[i][j+1] = -1
            toCheck.append([i,j+1])

    # bottom
    if i != rows-1:
        if population[i+1][j] > strength and population[i+1][j] != -1:
            population[i+1][j] = -1
            toCheck.append([i+1][j])

    if len(toCheck) == 0:
        return population

给我一​​个'TypeError'。虽然代码:

def answer(population, x, y, strength):

# make sure Z is infectable
if population[x][y] > strength:
    return population
else:
    population[x][y] = -1

# get array dimentions
rows = len(population)
cols = len(population[0])

# declare checking array
toCheck = [[]]
toCheck.append([x,y])

# loop 4 way check
while(1):
    #store and pop current element
    i = toCheck[0][0]
    j = toCheck[0][1]
    toCheck.pop(0)

    # left
    if j != 0:
        if population[i][j-1] <= strength and population[i][j-1] != -1:
            population[i][j-1] = -1
            toCheck.append([i,j-1])

    # top
    if i != 0:
        if population[i-1][j] < strength and population[i-1][j] != -1:
            population[i-1][j] = -1
            toCheck.append([i-1,j])

    # right 
    if j != cols-1:
        if population[i][j+1] > strength and population[i][j+1] != -1:
            population[i][j+1] = -1
            toCheck.append([i,j+1])

    # bottom
    if i != rows-1:
        if population[i+1][j] > strength and population[i+1][j] != -1:
            population[i+1][j] = -1
            toCheck.append([i+1][j])

    if len(toCheck) == 0:
        return population

给我和'IndexError'。这两个错误都发生在第i = toCheck [0] [0]行。 请帮忙!谢谢。

1 个答案:

答案 0 :(得分:0)

编辑:此回复是针对旧版本的问题代码。

假设您的所有代码都应该在funk()中:

一旦toCheck为空,您需要终止while循环。在弹出所有值后,原始版本会尝试索引空列表。试试这个:

# loop 4 way check
while len(toCheck) > 0:
    #store and pop current element
    i = toCheck[0][0]
    j = toCheck[0][1]
    toCheck.pop(0)

此外,在添加值之前,您无需声明toCheck。你可以替换

toCheck = [[],[]]
toCheck.append([x,y])

toCheck = [x, y]