【问题标题】:Stop a For Loop at an Index Value在索引值处停止 For 循环
【发布时间】:2019-10-18 01:36:03
【问题描述】:

我正在尝试使用 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('--------------------------------------')

【问题讨论】:

    标签: python loops selenium


    【解决方案1】:

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

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

    【讨论】:

    • 正是我需要的。谢谢。
    【解决方案2】:

    你可以使用 break 和 enumerate。

    for index, value in enumerate(train_times):
       if index == x : break
       // your code here
    

    【讨论】:

      【解决方案3】:

      你可以使用break 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, train in enumerate(train_times):
          if i == 400:
              break
          print('There is a train at {}'.format(train))
          print('--------------------------------------')
      

      查看更多关于循环中断的信息:https://docs.python.org/3.7/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多