简体   繁体   English

Python-再次循环最后一个元素

[英]Python - Loop last element again

a=[1,2,3,4]

for i in a:
    if someConditon:
        print(i)
    else:
        loop over last element again

I'm using selenium to interact with a webpage and download pdf documents. 我正在使用硒与网页交互并下载pdf文档。 Sometimes an error occurs during the download process and the file doesn't get saved. 有时在下载过程中会发生错误,并且不会保存文件。 The actual saving of the file exists in a for loop and I would like to add in a condition which 'if found to be false' loops over the same element again in an attempt to successfully download the item. 文件的实际保存存在于for循环中,我想添加一个条件,即“如果发现为假”则再次在同一元素上循环以尝试成功下载该项目。

My question is: How do I tell python to loop over the same element again 我的问题是:我如何告诉python再次遍历同一元素

There is no way to tell a for loop to not advance the iterator, so instead you will either need to use a while loop and manually increase i , or perform any additional looping within the body of your for loop. 没有办法告诉for循环不要推进迭代器,因此,您将需要使用while循环并手动增加i ,或者在for循环体内执行任何其他循环。 Here is how I would write this: 这是我的写法:

for i in a:
    while not someCondition:
        # do something
    print(i)

You can use a while loop and control when your index gets incremented. 您可以使用while循环并控制何时增加索引。 In this case i will only get incremented if the someCondtion is True. 在这种情况下,只有someCondtion为True时, i才会递增。 otherwise it will loop over the same element again and again. 否则,它将一次又一次地循环遍历同一元素。 You can add logic to avoid infinite repetitions, such as after X number of retries exit the loop or increment to the next index. 您可以添加逻辑以避免无限重复,例如在X次重试退出循环或递增到下一个索引之后。

a=[1,2,3,4]

while i < len(a):
    if someCondition:
        print a[i]
        i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM