[英]Python: Finding neighbouring duplicates in a list
首先……我是 Python 新手……如果這可能是您在這里看到的最基本的問題,我深表歉意。 從根本上說,我想解決 Kaggle Python(初學者)課程中的一個問題,以解決以下挑戰:
def menu_is_boring(meals):
"""Given a list of meals served over some period of time, return True if the
same meal has ever been served two days in a row, and False otherwise.
"""
我創建了以下嵌套 for 循環。 我的想法是,我可以通過這種方式將列表與自身進行比較,當我找到重復項時,它會返回 true:
for i in range(len(meals)):
for j in range(i+1, len(meals)):
if j == i:
return True
return False
輸入是:meals=['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']
所以我預計會出現“True”(連續 2 次垃圾郵件),但我的函數返回 False。 它看起來很容易..但顯然我錯過了一些東西。 也許我在這里缺少有關嵌套循環的一些基本知識。 我用谷歌搜索了嵌套循環用於重復的其他問題……但看不出與我所做的有明顯區別。
一個更簡單的解決方案是只使用一個循環並使用i + 1
作為你的第二個索引,但請注意你必須減少循環的長度,否則你會在最后一個循環周期超出界限。
for i in range(len(meals) - 1):
if meals[i] == meals[i + 1]:
return True
# iff no same meals at two days the loop doesnt return True
# and after loop is finished execute next code, which is return False
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.