Python IndexError: list assignment index out of range

Python IndexError: list assignment index out of range

由于 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

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

total_distance.append(sum(d))