为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2022-05-11 15:20:02
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 此链接包含代码和输出
查看完整描述

2 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

我刚刚纠正了逻辑错误。


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 False


checkList(number)


查看完整回答
反对 回复 2022-05-11
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

缩进不正确。如果你这样写:


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 False

zip(..)话虽如此,您可以通过在列表上移动一个位置的列表上进行迭代来以更优雅的方式解决此问题:


from itertools import islice


def 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


查看完整回答
反对 回复 2022-05-11
  • 2 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信