Loop til every element returns true

Viewed 82

I have a list with ids (list). Every element of that list returns a string 'true' or 'false' as a result of an online check with wget. I want to loop over that list, as long as there is a element returning a 'false' value. Basically I want to repeat this:

for i in range(len(list)):
  wget online check
  if status == 'true':
    write id to another list
  elif status == 'false':
    continue
  time.sleep()

over and over again until everything is true.

I tried it with a nested while loop:

for j in range(len(list)):
    while status_ == 'false':
        wget online check
      if status == 'true':
        write id to another list
      elif status == 'false':
        continue
      time.sleep()

But that doesn't work. Can anyone help please?

Cheers

4 Answers

Use a deque as a rotating queue, removing a value from the deque when it succeeds. The loop continues as long as the deque is not empty.

(A deque is like a list, but you can efficiently add elements to or remove elements from either end.)

from collections import deque

d = deque(list)

while d:
    i = d.popleft()
    wget online check
    if status == "true":
        write id to another list
    else:
        d.append(i)  # Put it back to try again later
    time.sleep(...)

You can try to store a value that is set to False everytime a False is met.

flag = False

while not flag:
    flag = True 
    for i in range(len(list)):
      wget online check
      if status == 'true':
        write id to another list
      elif status == 'false':
        flag = False
        continue
      time.sleep()

list is a bad name, I think you are after all(..) or any(..):

k = [True, False, False, True]
print(k)
while any(not i for i in k):   # loop as long as one value is False
    for i, v in enumerate(k):
        if not v:              # for demo purposes: change 1 False to True
            k[i] = True        
            break
    print(k)

print("done")

Output:

[True, False, False, True]
[True, True, False, True]
[True, True, True, True]
done

Documentation:

If I understand your question correctly, try to put a break at the end of the block where you get "true".

Hope it helps, have a nice day.

Related