简体   繁体   中英

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. 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.

My question is: How do I tell python to loop over the same element again

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. 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. In this case i will only get incremented if the someCondtion is True. 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.

a=[1,2,3,4]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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