【问题标题】:Loop til every element returns true循环直到每个元素都返回 true
【发布时间】:2020-10-21 21:05:39
【问题描述】:

我有一个带有 id 的列表(列表)。作为使用 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()

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

干杯

【问题讨论】:

  • status 总是一个字符串还是你可以把它变成一个布尔值?
  • 它总是一个字符串。更具体地说:状态写入一个文件中,该文件在发送检查请求时下载。

标签: python loops if-statement while-loop


【解决方案1】:

使用deque 作为旋转队列,成功时从双端队列中删除一个值。只要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(...)

【讨论】:

  • 我试过这个方法,但我得到:TypeError:序列索引必须是整数,而不是'str'。也许知道 ID 是字符串很重要。
【解决方案2】:

您可以尝试在每次遇到 False 时存储一个设置为 False 的值。

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

【讨论】:

    【解决方案3】:

    list 是个坏名字,我想你是all(..)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")
    

    输出:

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

    文档:

    【讨论】:

      【解决方案4】:

      如果我正确理解您的问题,请尝试将break 放在您获得"true" 的块的末尾。

      希望对你有所帮助,祝你有美好的一天。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2014-07-19
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        • 2017-12-05
        相关资源
        最近更新 更多