2 回答

TA貢獻1797條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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循環(huán)中,然后您 return False,并且您永遠不會讓您的程序查看其余元素。
您還應該使用len(List1)-1, not len(List1-1),因為您不能從列表中減去數(shù)字。
您可以通過移出循環(huán)來解決此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(..)話雖如此,您可以通過在列表上移動一個位置的列表上進行迭代來以更優(yōu)雅的方式解決此問題:
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
添加回答
舉報