Python For循环:如何';取一个';每次你经过的时候?
很抱歉标题含糊不清。我不知道该怎么说。 我需要做的是:我有一个电台列表,我需要打印我输入的电台之后的每个电台。我不知道如何完成它。我需要一个for循环。它应该是这样的:Python For循环:如何';取一个';每次你经过的时候?,python,for-loop,Python,For Loop,很抱歉标题含糊不清。我不知道该怎么说。 我需要做的是:我有一个电台列表,我需要打印我输入的电台之后的每个电台。我不知道如何完成它。我需要一个for循环。它应该是这样的: stations = ["Station A", "Station B", "Station C", "Station D"] begin = input("What is your begin station?") end = input("What is your end station?") for station in
stations = ["Station A", "Station B", "Station C", "Station D"]
begin = input("What is your begin station?")
end = input("What is your end station?")
for station in stations:
# This below should print every station after the 'begin' station. After it prints the first 'round' of stations,
# it has to continue to the next station, and print the stations after that.
print(station)
# If begin = "Station A"
# and end = "Station B"
# I want it to print the following:
# Station B
# Station C
# Station D
# (This would be the next time it passes over)
# Station C
# Station D
# (This would be the last time it passes over)
# Station D
您只需要开始电台的索引,然后使用内部循环从该索引+1循环到列表的长度,以打印从当前
i
到结束的所有电台:
stations = ["Station A", "Station B", "Station C", "Station D"]
begin = input("What is your begin station?")
end = input("What is your end station?")
ind = stations.index(begin) + 1
for i in range(ind, len(stations)):
for j in range(i,len(stations)):
print(stations[j])
print()
输出:
What is your begin station?Station A
What is your end station?Station B
Station B
Station C
Station D
Station C
Station D
Station D
不确定终端站如何安装,如果您真的想从终端站开始,请使用
ind=stations.index(end)
,不要+1
,请提出更具体的问题