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

问题描述 投票:0回答:1

此代码:

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

我试图避免使用普通的条件或循环并坚持理解。 这只是为了保持课程为每个学生设定的不言而喻的目标。

如果不扩展单一的理解,这是不可能的吗?

python arrays list indexing boolean
1个回答
0
投票

代码中的问题是您使用膳食 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) 的膳食相同。这避免了直接在餐串上使用索引。

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

© www.soinside.com 2019 - 2024. All rights reserved.