我将首先粘贴用于循环问题两次并输出文本的代码。然后我会将我改变它的那个粘贴到循环三次并尝试以英里为单位输出三个城市的距离。
我的城市和距离代码
cities=["Coventry", "Birmingham", "Wolverhampton", "Leicester"]
distances=[
[0,25,33,24],
[25,0,17,42],
[33,17,0,54],
[24,42,54,0]]
使用两个城市代码
def distancestwo():
choices=[0,1]
for j in range(2): #This will loop twice, hence giving the option for two cities. More could be added!
for i in range(len(cities)):
p.write ("%d : %s\n" %(i, cities[i]))
p.write("\nEnter city number %d: \n"%(j+1))
choices[j]=p.nextInt()
p.write("\n") #Leaves a line for the output of the distance
p.write("The distance between %s and %s is \n%d miles!\n"\
% (cities[choices[0]], cities [choices[1]],distances [choices[0]] [choices[1]]))
但是这个返回in对象不是可订阅的
def distancesthree():
choices=[0,1,2]
for j in range(3): #This will loop three times
for i in range(len(cities)):
p.write ("%d : %s\n" %(i, cities[i]))
p.write("\nEnter city number %d: \n"%(j+1))
choices[j]=p.nextInt()
p.write("\n") #Leaves a line for the output of the distance
p.write("The distance between %s ,%s and %s is \n %d miles!\n"\
% (cities[choices[0]], cities [choices[1]], cities [choices[2]],distances [choices[0]] [choices[1]] [choices[2]]))
答案 0 :(得分:1)
您尝试使用三个索引下标列表:
distances[choices[0]][choices[1]][choices[2]]
你可能想要像
这样的东西distances[choices[0]][choices[1]] + distances[choices[1][choices[2]]
下次,提供您获得的准确错误消息。
答案 1 :(得分:1)
你得到的错误是因为这部分:
distances [choices[0]] [choices[1]] [choices[2]]
您的2个城市的代码有效,因为distances
是包含城市之间距离的列表列表,因此distances[choices[0]][choices[1]]
首先选择第一个选定城市的距离列表,然后选择第二个城市:
dist_list = distances[choices[0]] #list of distances
distance_in_miles = dist_list[choices[1]] #entry for the selected city
因此,在新代码中,您尝试执行此操作:
result = distance_in_miles[choices[2]]
当然,你尝试索引的东西不是一个数字,而不是列表或字典等。
此外,您尝试做的事情甚至没有意义,因为三个点之间没有距离这样的事情。您可以计算从city1到city2到city3的距离或其中的任何排列,或者搜索访问这三个城市的最短路径,但只是要求“距离”没有任何意义。