You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表推导式实现连续重复检测报错及单推导式可行性咨询

问题:用列表推导式实现连续重复餐食判断函数报错,能否仅用推导式完成?

我编写了一段Python代码,试图通过列表推导式实现boring函数——该函数用于判断输入的meals列表中是否存在连续两天供应相同餐食的情况,存在则返回True,否则返回False。但运行时持续抛出IndexError: string index out of range错误。我希望避免使用普通条件语句或循环,仅通过单个推导式完成需求,请问这是否可行?

我的代码

"""this is a simple empty template in which to experiment"""
menu = ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']

def 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.
    """
    return [
        (
            i[meals.index(i)] == i[(meals.index(i) + 1)]
            )
            for i in meals if meals.index(i) < (len(meals)-1)
    ]

# This is the end of the doc
print(
    boring(menu)
)

报错信息

File "c:\work\Tester.py", line 10, in <listcomp>
    i[meals.index(i)] == i[(meals.index(i) + 1)]
                         ~^^^^^^^^^^^^^^^^^^^^^^
IndexError: string index out of range

问题分析与解决方案

错误原因

你的代码逻辑完全偏离需求:

  • i是列表中的餐食字符串(比如'Spam'),你写的i[meals.index(i)]是在取字符串的字符,而非列表中的下一个元素。比如meals.index('Spam')返回0,i[0]就是'S',当meals.index(i)+1超过字符串长度时,就会触发索引越界。
  • 另外meals.index(i)只会返回第一个匹配元素的索引,比如列表里多个'Spam',它始终返回0,根本无法遍历所有连续元素对。

可行的实现方案

完全可以仅用单个推导式(结合any()函数)完成需求,不需要普通循环或条件语句:

menu = ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']

def 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.
    """
    return any(meals[i] == meals[i+1] for i in range(len(meals)-1))

print(boring(menu))  # 输出: True

逻辑说明

  • range(len(meals)-1)生成从0到倒数第二个元素的索引,确保i+1不会超出列表范围。
  • 推导式(这里是生成器表达式,比列表推导式更省内存)遍历每个索引i,判断当前餐食和下一天餐食是否相等。
  • any()函数只要检测到任意一对连续相同的餐食,就立即返回True,完全符合函数需求。

内容的提问来源于stack exchange,提问作者hexicurse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:38:27