简体   繁体   English

Python:如何杀死无限循环?

[英]Python: How to kill a infinite for loop?

I have a for loop that goes into a list that has 10 items.我有一个 for 循环,它进入一个包含 10 个项目的列表。 For every item it has it adds 10 more to the list with the for loop.对于它拥有的每个项目,它使用 for 循环向列表中添加 10 个。 I want to kill the loop once the list length is 100 is this possible or I can't get out of the loop because the list never ends growing?一旦列表长度为 100,我想终止循环,这可能吗,或者我无法退出循环,因为列表永远不会增长?

This is my code:这是我的代码:

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)

I tried adding the following at the end but no luck我尝试在最后添加以下内容但没有运气


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


I see the print message when it hits 100, but it keeps going.当它达到 100 时,我看到了打印消息,但它一直在继续。

Any idea?任何的想法?

What if len(keywords) is never == 100 .如果len(keywords)永远不是== 100怎样。
Because keywords.append(k) is in a loop.因为keywords.append(k)处于循环中。
Example: len(keywords) == 98 and after loop len(keywords) become 103 .示例: len(keywords) == 98并且循环后len(keywords)变为103

Try to change the if statements to test if len(keywords) is greater or equal than 100 .尝试更改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

This is caused by you have 2 loops inside each other so you have to break twice, I don't think this is the most optimized solution, but it does the job:这是因为你有 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)

You should avoid modifying the list you're iterating through, because it can lead to strange behaviour.您应该避免修改您正在迭代的列表,因为它会导致奇怪的行为。 It would be better to have list of queries that haven't been tried out, which you deplete and fill up as you go, and a seperate loop (either for i in range(100) or a while loop with your break condition).最好有尚未尝试过的查询列表,您可以随时耗尽和填充这些查询,以及一个单独的循环( for i in range(100)或带有中断条件的 while 循环)。

As for the code you showed, there's two options, depending on where you placed the break condition.至于您显示的代码,有两个选项,具体取决于您放置中断条件的位置。

Version 1:版本 1:

Probably what you're doing可能你在做什么

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

Here, you only break the inner loop.在这里,您只会打破内部循环。 The outer keeps right on going, and so you have an infinite loop, since it keeps hitting the inner loop and then breaking out, again and again, because the outer loop is never terminated.外层继续前进,所以你有一个无限循环,因为它不断地击中内循环,然后一次又一次地爆发,因为外循环永远不会终止。

Version 2:版本 2:

Which still can easily produce an infinite loop.这仍然很容易产生无限循环。

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

Here, the outer loop would end.在这里,外循环将结束。 However, it might not, because the break condition is badly formulated.但是,它可能不会,因为中断条件制定得很糟糕。 Since you can add multiple words in each inner loop, len(keywords) might go from <100 to >100 without ever hitting the condition.由于您可以在每个内部循环中添加多个单词,因此len(keywords)可能会从<100变为>100而不会满足条件。 And then it never will, and you get an infinite loop again.然后它永远不会,你又得到一个无限循环。 Instead, it should be len(keywords) >= 100 , though then you will have cases where keywords is not exactly 100.相反,它应该是len(keywords) >= 100 ,尽管那样你会遇到keywords不完全是 100 的情况。

But the real answer is that you shouldn't be modifying the list you're iterating over in the first place, and restructure you're logic accordingly.但真正的答案是,您不应该首先修改您正在迭代的列表,并相应地重组您的逻辑。

Usually it's considered bad practice to modify a list while traversing it.通常在遍历列表时修改列表被认为是不好的做法。 That being said however, this is one way of doing it:然而,话虽如此,这是一种方法:

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)

A better way of doing it would be to use a second list and using the extend() function更好的方法是使用第二个列表并使用 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])

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM