【问题标题】:Python: How to kill a infinite for loop?Python:如何杀死无限循环?
【发布时间】:2021-01-05 02:46:54
【问题描述】:

我有一个 for 循环进入一个包含 10 个项目的列表。对于它拥有的每个项目,它都会使用 for 循环向列表中添加 10 个。一旦列表长度为 100,我想终止循环,这可能吗?或者我无法退出循环,因为列表永远不会结束增长?

这是我的代码:

keywords = [
"apple store",
"applesauce recipe",
"applesauce",
"appleseeds",
"apples to apples",
"apples and honey",
"applesauce cake",
"apple support",
"apples and bananas"
]

   for i in keywords:
            url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
            response = requests.get(url, verify=False)
            suggestions = json.loads(response.text)
            for word in suggestions[1]:
                k = word
                keywords.append(k)
                print(word)

我尝试在最后添加以下内容,但没有成功


if len(keywords) == 100:
    print('this is where it needs to break')
    break


当它达到 100 时,我看到了打印消息,但它一直在运行。

有什么想法吗?

【问题讨论】:

  • 我认为您附加到关键字,它是您正在循环的列表,这可能会不断增长。尝试在每次迭代结束时打印len(keywords)。另外,不需要将word设置为k,只需附加word
  • 是的,我确实添加了 print len(keywords) 并不断增长。我想在 len 为 100 时杀死它。
  • break 终止最近的包装范围,也许您终止了内部循环但外部循环仍在循环?
  • 哦,明白了!我需要将 if else 移到外循环!现在它起作用了。谢谢sss
  • 我在设置 len(keywords) == 1000 时遇到了一些问题。出于某种原因,它达到了 1000,但它一直在运行

标签: python for-loop logic


【解决方案1】:

如果len(keywords) 永远不会是== 100
因为keywords.append(k) 处于循环中。
示例:len(keywords) == 98 和循环后 len(keywords) 变为 103

尝试更改if 语句以测试len(keywords) 是否大于或等于100

for i in keywords:
    url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
    response = requests.get(url, verify=False)
    suggestions = json.loads(response.text)
    for word in suggestions[1]:
        keywords.append(word)
        print(word)

    if len(keywords) >= 100:  # test if greater or equal than 100
        print('this is where it needs to break')
        break

【讨论】:

    【解决方案2】:

    这是因为你有 2 个循环,所以你必须打破两次,我不认为这是最优化的解决方案,但它可以工作:

    import requests
    import json
    
    keywords = [
    "apple store",
    "applesauce recipe",
    "applesauce",
    "appleseeds",
    "apples to apples",
    "apples and honey",
    "applesauce cake",
    "apple support",
    "apples and bananas"
    ]
    
    for i in keywords:
        url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
        response = requests.get(url, verify=False)
        suggestions = json.loads(response.text)
        if len(keywords) == 100:
            print('this is where it needs to break')
            break
        else:
            for word in suggestions[1]:
                if len(keywords) == 100:
                    print('this is where it needs to break')
                    break
                else:
                    keywords.append(word)
                    print(word)
    

    【讨论】:

      【解决方案3】:

      您应该避免修改您正在迭代的列表,因为它会导致奇怪的行为。最好有一个尚未尝试过的查询列表,您可以随时将其耗尽并填充,以及一个单独的循环(for i in range(100) 或带有中断条件的 while 循环)。

      至于您显示的代码,有两个选项,具体取决于您放置中断条件的位置。

      版本 1:

      可能你在做什么

      for i in keywords:
          url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
          response = requests.get(url, verify=False)
          suggestions = json.loads(response.text)
          for word in suggestions[1]:
              k = word
              keywords.append(k)
              print(word)
      
              if len(keywords) == 100:
                  print('this is where it needs to break')
                  break
      

      在这里,你只打破了内部循环。外循环一直在运行,所以你有一个无限循环,因为它不断撞击内循环,然后一次又一次地中断,因为外循环永远不会终止。

      版本 2:

      这仍然很容易产生无限循环。

      for i in keywords:
          url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
          response = requests.get(url, verify=False)
          suggestions = json.loads(response.text)
          for word in suggestions[1]:
              k = word
              keywords.append(k)
              print(word)
      
          if len(keywords) == 100:
              print('this is where it needs to break')
              break
      

      到此,外循环将结束。但是,它可能不会,因为中断条件的制定很糟糕。由于您可以在每个内部循环中添加多个单词,len(keywords) 可能会从<100 变为>100 而不会满足条件。然后它永远不会,你又得到一个无限循环。 相反,它应该是len(keywords) >= 100,不过你会遇到keywords 不完全是100 的情况。

      但真正的答案是,您不应该首先修改您正在迭代的列表,并相应地重组您的逻辑。

      【讨论】:

      • 知道了。现在它是有道理的。我打到了100,但它一直在继续。现在 >= 停在 104 或接近该位置。非常感谢
      【解决方案4】:

      通常,在遍历列表时修改列表被认为是不好的做法。话虽如此,这是一种方法:

      keywords = [
      "apple store",
      "applesauce recipe",
      "applesauce",
      "appleseeds",
      "apples to apples",
      "apples and honey",
      "applesauce cake",
      "apple support",
      "apples and bananas"
      ]
      
      for i in keywords:
          url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
          response = requests.get(url, verify=False)
          suggestions = json.loads(response.text)
          if len(keywords) >= 100:
              print('this is where it needs to break')
              break
          for word in suggestions[1]:
              k = word
              keywords.append(k) if len(keywords) < 100 else 0 # you can put basically anything here insetad of 0
              print(word)
      
      

      更好的方法是使用第二个列表并使用 extend() 函数

      keywords = [
      "apple store",
      "applesauce recipe",
      "applesauce",
      "appleseeds",
      "apples to apples",
      "apples and honey",
      "applesauce cake",
      "apple support",
      "apples and bananas"
      ]
      
      new_keywords = list(keywords) # storing a copy of keywords in new_keywords
      
      for i in keywords:
          url = "http://suggestqueries.google.com/complete/search?output=firefox&q=" + i
          response = requests.get(url, verify=False)
          suggestions = json.loads(response.text)
          
          new_keywords.extend(suggestions[1])
      
      

      【讨论】:

        【解决方案5】:

        您需要检查循环之前的长度。这将限制循环继续进行。

        【讨论】:

        • 你能举个例子吗?我不能很好地理解它。我希望我的列表只增长到 100
        • 如何在循环 for i 的位置添加条件。添加 'AND' 和 len(关键字)。它应该可以工作。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-30
        • 2023-04-06
        • 2011-12-19
        • 2014-05-07
        • 1970-01-01
        • 2014-01-14
        • 2013-08-04
        相关资源
        最近更新 更多