Train_stations = [ "Perrache", "Ampere", "Bellecour", "Cordeliers", "Louis", "Massena" ]我开始这样做:
start_station = input("Where are you now?")
ending_station = input("Where would you like to go,")
final = range(start_station) - range(ending_station)
print(final)它不起作用,因为显然我不能使用这种类型的值的范围。
发布于 2018-10-06 23:09:52
如何获取列表中事物的索引差异:使用the index() method:
Train_stations = [ "Perrache", "Ampere", "Bellecour", "Cordeliers", "Louis", "Massena" ]
start_station = ""
ending_station = ""
while start_station not in Train_stations:
print("Possible inputs: ", Train_stations)
start_station = input("Where are you now?")
while ending_station not in Train_stations:
print("Possible inputs: ", Train_stations)
ending_station = input("Where would you like to go?")
idx_start = Train_stations.index(start_station)
idx_end = Train_stations.index(ending_station)
print("The stations are {} stations apart.".format ( abs(idx_start-idx_end)))输出:
Possible inputs: ['Perrache', 'Ampere', 'Bellecour', 'Cordeliers', 'Louis', 'Massena']
Where are you now?Ampere
Possible inputs: ['Perrache', 'Ampere', 'Bellecour', 'Cordeliers', 'Louis', 'Massena']
Where would you like to go?Perrache
The stations are 1 stations apart.发布于 2018-10-06 23:06:36
如果目标是获得站点indexes之间的距离,您可以简单地使用.index()并取差值的abs()。
train_stations = [ "Perrache", "Ampere", "Bellecour", "Cordeliers", "Louis", "Massena" ]
start_station = input("Where are you now: ")
ending_station = input("Where would you like to go: ")
final = abs(train_stations.index(start_station) - train_stations.index(ending_station))
print(final)
# Perrache Bellecour = > 2https://stackoverflow.com/questions/52680207
复制相似问题