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)
它不起作用,因为显然我不能用这种类型的值来用户设置范围。
答案 0 :(得分:2)
如何获取列表内事物的索引差异:使用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.
答案 1 :(得分:1)
如果目标是获得站点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 = > 2