Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - For-Loop: How to 'take one off' every time you pass over?

Sorry for the vague title. I have no idea how to put it. What I need to do: I have a list of stations, I need to print every station that comes after the station I put in. I have no idea how to accomplish it. I need to do it with a for loop. This is what it should look like:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need the index of the begin station then loop from that index + 1 to the length of the list using an inner loop to print all the stations from the current i to the end:

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()

Output:

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

Not sure how the end station fits into it, if you actually want to start from the end station then use ind = stations.index(end) and don't + 1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...