2017-08-23 96 views
-1

由於total_distance[counter4] = sum(d)行我收到此錯誤。我不知道是什麼原因造成的,我給d添加了值,並簡單地將它們相加並將它們賦值給一個數組中的索引。什麼導致了這個錯誤?Python IndexError:列表分配索引超出範圍

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 
+3

如果你想添加一些東西到列表的末尾,使用'total_distance.append(sum(d))'。除非counter4 khelwood

+0

'total_distance + = [sum(d)]'也有效 – Aemyl

回答

0

使用'append'將值添加到空列表中。就像你之前做的那樣。

total_distance.append(sum(d)) 
相關問題