points = [(1, 41, altitudes[41][1]), (46, 71, altitudes[71][46]), (29, 37, altitudes[37][29]), (75, 52, altitudes[52][75]), (66, 44, altitudes[44][66])] best_site = [62, 51, altitudes[51][62]] # 计算距离矩阵 dist_matrix = [[math.sqrt((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2 + (altitudes[1][i] - altitudes[1][j]) ** 2) for j in range(5)] for i in range(5)] # 定义适应度函数 def fitness(solution): total_distance = 0 total_distance = total_distance + dist_matrix[best_site][solution[0]] for i in range(4): total_distance += dist_matrix[solution[i]][solution[i+1]] total_distance = total_distance + dist_matrix[solution[4]][best_site] return total_distance产生上述报错
时间: 2023-06-30 13:20:07 浏览: 54
吉他谱_Altitudes - Jason Becker.pdf
在 `fitness` 函数中,`best_site` 是一个列表,而在计算总距离时,使用了 `best_site` 作为索引,导致了 `TypeError` 错误。需要将 `best_site` 的值改为对应的整数值。
例如,将 `best_site` 改为 `51`:
```python
best_site = 51
```
然后在计算总距离时,就可以使用整数值作为索引:
```python
total_distance = total_distance + dist_matrix[best_site][solution[0]]
total_distance = total_distance + dist_matrix[solution[4]][best_site]
```
注意,这里需要将 `best_site` 作为第二个索引使用,因为 `dist_matrix` 是一个二维列表,需要同时指定行和列的索引。
阅读全文