如何计算lis中两个值之间的位置差

2024-06-01 05:57:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

它不起作用,因为显然我不能使用这种类型的值来设置用户范围


Tags: youinputendingrangetrainwherestartfinal
2条回答

如何获取列表中事物的索引差异:使用the ^{} 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.

如果目标是获得站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

相关问题 更多 >