python - 在索引值处停止 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('--------------------------------------')
解决方案
正如您知道要在字符串中停止的确切索引一样,您可以提供要循环的索引
for i in train_times[:20]:
print('There is a train at {}'.format(i))
print('--------------------------------------')
推荐阅读
- python - 有没有办法使用 for 循环从索引中删除特定字符串?
- windows - 如何在 Windows 32 位上运行 Redis?
- flask-restplus - 动态生成 Flask-RESTPlus 路由
- node.js - 文件更改不会触发节点服务器的重新加载
- bash - Bash 执行 while 循环以检查 Fedora 30 中与 nmcli 的 VPN 连接
- php - 通过 Laravel 发送邮件不一致
- laravel - ID和连接
- c# - DynamoDB 条件 SaveAsync
- angular - 从 WebStorm Jest Testrunner 开始,Jest 单元测试不起作用
- azure-devops - 部署后文件已被删除