简体   繁体   English

为什么在类似的循环有效时此循环不起作用?

[英]Why this loop doesn't work while the similar one works?

This function should return True if the list "nums" contains a 3 next to a 3 somewhere. 如果列表“ nums”在某处3旁边包含3,则此函数应返回True。

The function "has_33" should accept a list argument, so this loop works perfectly :- 函数“ has_33”应接受列表参数,因此此循环可完美运行:-

def has_33(nums):
    for i in range(0, len(nums)-1):

        if nums[i:i+2] == [3,3]:
            return True  

    return False

But when I do it in this form :- 但是当我以这种形式做它时:-

def has_33(nums):
    for i in range(0,len(nums)-1):  

        if nums[i:i+2] == [3,3]:
            return print("True")
        else:
            if i == len(nums)-1:
                return print("False")

it fails to print "False" if the array doesn't include the condition. 如果数组不包含条件,则无法打印“ False”。

So why the first loop works while the second loop doesn't work although they are the same? 那么,为什么第一个循环可以工作而第二个循环却不能工作,尽管它们是相同的?

You should not put this condition: 您不应该提出以下条件:

if i == len(nums)-1:

inside your function. 内部功能。 And even if you do, use: 即使这样做,也请使用:

if i == len(nums)-2:

because i will never become len(nums)-1 (see the loop condition above) 因为i永远不会成为len(nums)-1 (请参见上面的循环条件)

num == len(nums)-1 never evaluates True , because num is a list, not an integer. num == len(nums)-1永远不会求值为True ,因为num是一个列表,而不是整数。

The bigger issue at hand is though, that this whole else clause is unnecessary, as you can just let python exit the loop, and then print("False"). 不过,更大的问题是,整个else子句是不必要的,因为您可以让python退出循环,然后执行print(“ False”)。 Additionally,'i suggest the following solution: 另外,我建议以下解决方案:

from itertools import tee


def has_33(nums):
    num1, num2 = tee(nums)
    next(num2)
    for a, b in zip(num1, num2):
        if [a, b] == [3, 3]:
            print("True")
            return
    print("False")

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

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