首页 > 解决方案 > 在索引值处停止 For 循环

问题描述

我正在尝试使用 for 循环来遍历项目列表。我不需要列表中的所有项目,并希望在某个索引位置结束。我将如何在 python 中解决这个问题?

我试图使用枚举并将我的代码更改为其他选项。经过数小时的搜索,我很难理解如何根据 python 中的某个参数结束循环。我提供的代码非常适合我的兴趣。我只想在某个索引上停止 for 循环。

train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i in train_times:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')

标签: pythonloopsselenium

解决方案


正如您知道要在字符串中停止的确切索引一样,您可以提供要循环的索引

for i in train_times[:20]:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')

推荐阅读