【问题标题】:Incrementing Python loop counter inside the loop without IndexError: list index out of range在没有 IndexError 的情况下在循环内递增 Python 循环计数器:列表索引超出范围
【发布时间】:2020-05-18 13:37:09
【问题描述】:

我正在尝试按照 docstring 中的说明创建此函数,但要么我只通过了第一个 doctest,要么因 IndexError: list index out of range 而失败。如果我能以某种方式在循环内再次增加循环计数器而不会超出范围,我觉得这种当前的方法会起作用。我试过了

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.

>>> menu_is_boring(['Egg', 'Spam'])
False
>>> menu_is_boring(['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam'])
True

"""
for i in range(len(meals)):
    x = (meals[i] == meals[i+1]) and (meals[i] == meals[i+2])
return x

为了解决索引错误,我尝试使用 while 循环,但由于语法错误而失败:

for i in range(len(meals)):
    x = (meals[i] == meals[(while i<len(meals): i+=1 )]) and (meals[i] == meals[while i<len(meals):i+=2])

嵌套循环会以某种方式起作用,还是我过于复杂了?

附:该问题有可用的解决方案,但我试图查看我的方法有什么问题或获得提示,而不是直接跳到解决方案。这是我的第一个问题,所以如果它没有遵循所有准则,请原谅。

【问题讨论】:

  • 您不能将i 增加为i+=1 并将其用作索引。这就是导致语法错误的原因。索引错误是因为您试图访问meals[i+2]i 的最大值是 meals 的最后一个索引,因此为避免索引错误,您只能迭代到 range(len(meals)-2)
  • 您的代码中的逻辑错误是,每次通过循环时,您替换您对菜单是否无聊的评估与最近比较的结果;但是一旦你发现菜单很无聊,它在逻辑上就不会再变得有趣了。

标签: python loops increment


【解决方案1】:

只记得最后一顿饭:

def menu_is_boring(meals):
    last = None
    for meal in meals:
        if meal == last:
            return True
        last = meal
    return False

【讨论】:

    【解决方案2】:

    您似乎正在使用x = (meals[i] == meals[i+1]) and (meals[i] == meals[i+2]) 连续检查 3 天。此外,IndexError 是由于您尝试使用n 元素访问列表的n+1thn+2th 元素引起的。为避免这种情况,您应该根据需要运行循环直到 n-1n-2

    所以你要做的就是:

    for i in range(len(meals)-1):  # Run the loop till n-1
        x = meals[i] == meals[i+1] # Check for nth and n+1th meal to be same
    return x
    

    话虽如此,本节将无法解决您的问题,并且将始终返回最后一餐对的值,因为 x 在循环的每次迭代中都会被覆盖。为了解决这个问题,您可以在找到重复项后立即返回 True

    def menu_is_boring(meals):
        for i in range(len(meals)-1):
            if meals[i] == meals[i+1]:
                return True
        return False
    

    您可以通过调用函数并打印其返回值来测试它。

    print (menu_is_boring(['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']))
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2019-05-21
      • 2019-02-07
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      相关资源
      最近更新 更多