简体   繁体   English

While循环Python中的While循环

[英]While-loop within a while-loop python

I am trying to write a while-loop within a while-loop, and for some reason it is not working as it should. 我正在尝试在while循环内编写一个while循环,由于某种原因,它无法正常工作。 I know I'm probably missing something really trivial here, but I just don't understand how its not working! 我知道我可能在这里错过了一些琐碎的事情,但是我只是不明白它是如何工作的!

The purpose of the loop is to compare two strings to see whether or not they contain any 3 consecutive words the same. 循环的目的是比较两个字符串,以查看它们是否包含相同的三个连续单词。 I first split the two strings into lists of their respective 3 word string combinations which I store in the lists strings and stringscompare. 我首先将两个字符串分成各自的3个单词字符串组合的列表,然后将它们存储在列表中的string和stringscompare。 Then I loop through each 3 word string in stringscompare for each 3 word string in strings. 然后,我遍历字符串中的每个3字字符串,比较字符串中的每个3字字符串。

This will probably seem like a pretty long way round for some but I am only a novice programmer, any improvements would be greatly appreciated. 对于某些人来说,这似乎很漫长,但是我只是一个新手程序员,任何改进将不胜感激。

So currently, the second while loop runs all the way through, however the first one only loops through once, for the first string in strings. 因此,目前,第二个while循环一直贯穿整个过程,但是对于字符串中的第一个字符串,第一个while循环仅循环一次。 If the string matches I would like it to break from both loops, however these loops are also in a much bigger for loop which I don't want it to break out of. 如果字符串匹配,我希望它从两个循环中都断开,但是这些循环也位于for循环中,这是我不希望其中断的更大的循环。

eg 例如

'this is a string' '这是一个字符串'
'this is another string' --no match '这是另一个字符串'-不匹配
'this is a list a strings' -- matches 'this is a' '这是一个字符串列表'-匹配'this is a'
'the list is a string' -- should match 'is a string' but currently does not '列表是一个字符串'-应该匹配'is a string'但当前不匹配

strings = <list of 3 word strings> [...,...,...]
stringscompare = <list of 3 word strings to compare>
v=0, x=0
while v < len(strings) and stop == False:
    while x < len(stringscompare) and stop == False:
        if re.search(strings[v], stringscompare[x]):
            same.append(dict)
            stop = True
        x += 1
    v +=1

You never reset x inside the outer loop. 您永远不会在外循环内重置x As a result it'll always be equal or greater to len(stringscompare) after the first iteration of the outer loop. 结果,它在外循环的第一次迭代之后将始终等于或大于len(stringscompare)

Set it to 0 in the outer loop: 外部循环中将其设置为0

v = 0
while v < len(strings) and stop == False:
    x = 0
    while x < len(stringscompare) and stop == False:

Other observations: 其他观察:

Don't use stop == False where not stop will do. 不要使用stop == False ,在not stop会做。

You could just use a for loop, then break out twice: 您可以只使用for循环,然后中断两次:

for s in strings:
    for sc in stringscompare:
        if re.search(s, sc):
            same.append(dict)
            break
    else:
        continue
    # only reached if the inner loop broke out
    break

or use any() with a generator expression to find the first match: 或使用带有生成器表达式的any()来查找第一个匹配项:

 if any(re.search(s, sc) for s in strings for sc in stringscompare):
     same.append(dict)

you use twice the same variable stop I think you should set the stop to false after the loop: 您使用两次相同的变量stop我认为您应该在循环后将stop设置为false:

strings = <list of 3 word strings> [...,...,...]
stringscompare = <list of 3 word strings to compare>
v=0, x=0
while v < len(strings) and stop == False:
    while x < len(stringscompare) and stop == False:
        if re.search(strings[v], stringscompare[x]):
            same.append(dict)
            stop = True
        x += 1
    stop = False
    v +=1

I would suggest something like this.. 我建议像这样。

strings = [] # <list of 3 word strings> [...,...,...]
stringscompare = [] # <list of 3 word strings to compare>

stop = False

for x in strings:
    if stop:
        break

    for v in stringscompare:
        if re.search(v, x):
            stop = True
            break

A for loop seems a lot more appropriate here. for循环在这里似乎更合适。 Is this what you're trying to achieve? 这是您要达到的目标吗?

Well the most obvious problem with the code here is that you do not set the value of X to be 0 again once the inner loop finishes. 好的,这里的代码最明显的问题是,一旦内部循环结束,您就不必再将X的值设置为0了。 I'll explain: Lets say both 'strings' and 'stringscompare' length is 3. When you first enter the big while loop, v=0 and x=0. 我将说明:假设“字符串”和“字符串比较”的长度均为3。当您第一次进入big while循环时,v = 0和x = 0。 When we enter the second loop, x=0. 当我们进入第二个循环时,x = 0。 When we leave the second loop, if no match was found, x = length(stringscompare) = 3. 当我们离开第二个循环时,如果找不到匹配项,则x = length(stringscompare)= 3。

Now, when we go back to the first while loop it DOES actually go inside the loop again - but it does nothing, as the clause for the 2nd loop cannot be satisfied - X is still 3! 现在,当我们回到第一个while循环时,它实际上确实又进入了循环-但是它什么也没做,因为不能满足第二个循环的子句-X仍然是3!

You can fix this by resetting X at the end of loop 2: 您可以通过在循环2的结尾处重置X来解决此问题:

strings = <list of 3 word strings> [...,...,...]
stringscompare = <list of 3 word strings to compare>
v=0, x=0
while v < len(strings) and stop == False:
    while x < len(stringscompare) and stop == False:
        if re.search(strings[v], stringscompare[x]):
            same.append(dict)
            stop = True
        x += 1
    x = 0 #resetting X
    v +=1

You can easily track downs problems like this one by debugging. 您可以通过调试轻松跟踪此类问题。 There are many methods to debugging, its an art really :P What I would recommend for you: 有很多调试方法,这实际上是一种艺术:P我为您推荐的是:

  1. If your'e using Eclipse, PyCharm, etc, you can use the built in debuggers which are amazing. 如果您使用的是Eclipse,PyCharm等,则可以使用内置的调试器,这很棒。 You can stop at any point of the program by adding breakpoints, see the value of all the variables, etc. For example, in this case, I would put a breakpoint on the first loop statement ('while v < len...'). 您可以通过添加断点来停止程序的任何位置,查看所有变量的值,等等。例如,在这种情况下,我将在第一个循环语句上放置一个断点(“ while v <len ...” )。 That way, you couldv easly see that the first loop is in fact running, and its the second loop thats the problem. 这样,您可以轻松地看到第一个循环实际上正在运行,而第二个循环就是问题所在。

  2. Printing is your friend. 印刷是您的朋友。 Something simple like this for example: 像这样简单的事情:

 v=0, x=0 while v < len(strings) and stop == False: print "About to enter second loop..." while x < len(stringscompare) and stop == False: if re.search(strings[v], stringscompare[x]): same.append(dict) stop = True x += 1 v +=1 

You could also print the values of variables btw. 您还可以打印变量btw的值。

There are many other ways to do what you're trying to do (triangle graphs, advanced search methods, maybe a more complex data structure, etc). 还有许多其他方法可以执行您要执行的操作(三角图,高级搜索方法,也许是更复杂的数据结构等)。 But for now - I think the best thing for you is to solve problems in the most straightforward way you can - focus on writing quality code (well named variables, indents, comments etc). 但是就目前而言-我认为对您来说最好的办法是以最直接的方式解决问题-专注于编写高质量的代码(命名变量,缩进,注释等)。 The geeky, 'top performance' cutting edge tricks will come in later :) 令人讨厌的,“顶级性能”的最新技巧将在以后出现:)

Good luck and have fun! 祝好运并玩得开心点!

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

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