检查一个数字是否在同一个数字之前,但没有从代码中得到任何输出

number =[2,3,4,9,9,5,1]

def checkList(List1):

    for i in range(len(List1 - 1)):


if List1[i] == 9 and List1[i+1] == 9:

            return True

    return false

此代码不输出任何值,无论是真还是假,假设如果 9 在 9 之后输出 true,否则输出 false [在此处输入图像描述][1]


[1]:https ://i.stack.imgur.com/kwm0S.png 此链接包含代码和输出


手掌心
浏览 126回答 2
2回答

互换的青春

我刚刚纠正了逻辑错误。number = [2, 3, 4, 9, 8, 5, 1]def checkList(List1):    for i in range(len(List1) - 1):        if List1[i] == 9 and List1[i + 1] == 9:            return True    return FalsecheckList(number)

拉风的咖菲猫

缩进不正确。如果你这样写:def checkList(List1):    for i in range(len(List1 - 1)):        if List1[i] == 9 and List1[i+1] == 9:            return True        return False那么这意味着从if检查失败的那一刻起,它将返回False。所以这意味着如果前两项不是 both 9,则if失败,但在您的for循环中,然后您 return False,并且您永远不会让您的程序查看其余元素。您还应该使用len(List1)-1, not len(List1-1),因为您不能从列表中减去数字。您可以通过移出循环来解决此return False问题for:def checkList(List1):    for i in range(len(List1)-1):        if List1[i] == 9 and List1[i+1] == 9:            return True    return Falsezip(..)话虽如此,您可以通过在列表上移动一个位置的列表上进行迭代来以更优雅的方式解决此问题:from itertools import islicedef checkList(iterable):    return any(x == y == 9 for x, y in zip(iterable, islice(iterable, 1, None)))例如:>>> checkList([2,3,4,9,9,5,1])True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python