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)
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
添加回答
举报