好的,所以我有一个包含四个不同城市的程序,每个城市都有距离。该程序将询问用户他们想要计算哪些城市,并以英里为单位返回两个城市之间的距离。现在我有一个工作循环,要求用户输入城市 1,然后输入城市 2,一旦完成,程序将返回两个城市之间的距离。但是我随后尝试做同样的事情,但要求用户选择三个不同的城市,然后返回三个城市之间的距离。除了返回“int object is not subscriptable”之外,代码实际上是相同的
我将首先粘贴用于循环问题两次并输出文本的代码。然后,我将粘贴已更改为循环三次的那个,并尝试以英里为单位输出三个城市的距离。
我的城市和距离代码
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]]))