首页 > 解决方案 > 循环直到每个元素都返回 true

问题描述

我有一个带有 ids 的列表(列表)。作为使用 wget 进行在线检查的结果,该列表的每个元素都会返回一个字符串“true”或“false”。我想遍历该列表,只要有一个元素返回“假”值。基本上我想重复一下:

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

一遍又一遍,直到一切都是真的。

我用嵌套的while循环尝试了它:

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()

但这不起作用。有人可以帮忙吗?

干杯

标签: pythonloopsif-statementwhile-loop

解决方案


使用 adeque作为旋转队列,成功时从双端队列中删除一个值。只要deque不为空,循环就会继续。

(双端队列就像一个列表,但您可以有效地向任一端添加元素或从中删除元素。)

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

推荐阅读