程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

索引/数组故障排除:家庭作业

发布于2023-11-18 10:24     阅读(10278)     评论(0)     点赞(24)     收藏(0)


这段代码:

"""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 的索引作为访问 i 中元素的索引。这可能会导致 IndexError,因为索引是一个整数,但 i 是一个字符串(在本例中是一顿饭)。在列表理解中,您应该直接迭代元素,而不是它们的索引。

这是使用列表理解的代码的更正版本:

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))

在此版本中,any 用于检查是否有任何连续几天吃同一顿饭。列表推导式迭代膳食索引,并且 Meals[i] == Meals[i + 1] 检查第 i 天的膳食是否与第二天 (i + 1) 的膳食相同。这避免了直接在餐串上使用索引。

这应该会给你想要的结果,而不会超出单一的理解。



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2039601/52bab686891903bd0d38/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

24 0
收藏该文
已收藏

评论内容:(最多支持255个字符)