首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算列表中两个值的位置差

如何计算列表中两个值的位置差
EN

Stack Overflow用户
提问于 2018-10-06 22:48:22
回答 2查看 31关注 0票数 1
代码语言:javascript
复制
Train_stations = [ "Perrache", "Ampere", "Bellecour", "Cordeliers", "Louis", "Massena" ]

我开始这样做:

代码语言:javascript
复制
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)

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

EN

回答 2

Stack Overflow用户

发布于 2018-10-06 23:09:52

如何获取列表中事物的索引差异:使用the index() method

代码语言:javascript
复制
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)))

输出:

代码语言:javascript
复制
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.
票数 2
EN

Stack Overflow用户

发布于 2018-10-06 23:06:36

如果目标是获得站点indexes之间的距离,您可以简单地使用.index()并取差值的abs()

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52680207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档