Home > Software engineering >  How to skip an iteration of a loop after some time in Python?
How to skip an iteration of a loop after some time in Python?

Time:04-27

I have a code with a loop that I need to skip an iteration if it is taking too much time.

Example:

list = ['a', 'b', 'c', ......]

for x in list:

    #do something that takes time


I want to skip an item of the time of running the script is bigger than, let's say, 30 minutes?

CodePudding user response:

I assume you mean that you want to break out of the loop if a certain amount of time has elapsed. If so, take a look at the time module. You can use features from there to note the time before you enter the loop then, at appropriate points in the code, compare the elapsed time from your initial record of the start time and continue accordingly

CodePudding user response:

You might like this code

import pprint as p
llist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
HashMap = {}
for i, x in enumerate(llist):
    HashMap[x] = i
    # Your condition
    if len(HashMap) > 20:
        break  # You can do continue 

p.pprint(HashMap, width = 200, sort_dicts = False)

Explanation

Imported pprint to print beautifully

changed the var name from list to llist because I don't want to mask built-ins

Created a dictionary HashMap to store the index of the items and the items

looped on llist using enumerate() to get those indices

After loop first step was to append the item to HashMap so that we keep the count

Then the condition will come.....

Then checking length of HashMap, if it exceed the condition then break

Finally to print it

  • Related