Python IndexError:列表赋值索引超出范围

时间:2017-08-23 12:54:38

标签: python index-error

由于total_distance[counter4] = sum(d)行,我收到此错误。我不知道是什么导致它,我有附加值到d,我只是将它们相加并将该值赋给数组中的索引。导致此错误的原因是什么?

total_distance= []
d=[]
all_city = []
lowest_distance = 0

for permutation in itertools.permutations(city,len(city)):
   all_city.append(permutation)

for l in all_city:
    z = []
    q = 0
    counter4 = 0
    while q < len(city):
        z.append(int(l[q]))
        q = q+1
    for m in z:
        n = m - 1
        first_index = 0
        counter1 = 0
        if counter < len(z):
            checktime(initial_time1,time_limit1,total_distance)
            if counter1 == 0:
                first_index = n

            d.append(math.sqrt(math.pow((int(float(x[n + 1])) - int(float(x[n]))), 2) + math.pow((int(float((y[n + 1]))) - int(float(y[n]))), 2)))

        elif counter1 == len(z):
            checktime(initial_time1, time_limit1,total_distance)
            d.append(math.sqrt(math.pow((int(float(x[n]))-int(float(x[first_index]))), 2)+math.pow((int(float(y[n]))-int(float(y[first_index]))),2)))

        counter1 = counter1 + 1

    total_distance[counter4] = sum(d) # ERROR LINE
    counter4 = counter4 + 1

1 个答案:

答案 0 :(得分:0)

使用'append'将值添加到空列表。正如你之前所做的那样。

total_distance.append(sum(d))