我目前正在为学校做一次小作业。
我需要打印当前火车所在的当前车站以及列表中剩余的车站。
我使用了嵌套的for
循环,但无法获取内部的for
循环以正常工作。我是否需要使用+=1
创建变量?
我的代码:
train_station=['Amsterdam-Central','Amsterdam-Amstel','Utrecht']
for x in train_station:
print("Current station is: "+x)
print("Stations to go: ")
begin=0
for y in range(begin,3,1):
print(train_stations[y])
我的输出:
Current station is: Amsterdam-Central
Stations to go:
Amsterdam-Central
Amsterdam-Amstel
Utrecht
Current station is: Amsterdam-Amstel
Stations to go:
Amsterdam-Central
Amsterdam-Amstel
Utrecht
Current station is: Utrecht
Stations to go:
Amsterdam-Central
Amsterdam-Amstel
Utrecht
最佳答案
差不多完成了,您只需要在每次迭代中增加begin
即可。
train_station=['Amsterdam-Central','Amsterdam-Amstel','Utrecht']
begin = 0
for x in train_station:
print("Current station is: "+x)
print("Stations to go: ")
begin += 1
for y in range(begin, 3, 1):
print(train_station[y])
还有一个更Python化的解决方案:
for i, x in enumerate(train_station, 1):
print("Current station is: "+x)
print("Stations to go: ")
for y in train_station[i:]:
print(y)