python中递减列表中的索引器

2024-06-16 14:05:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生,经常会遇到这个错误。我需要知道代码有什么问题,当使用range()传递递减列表时它不会执行: 我ndexError:列表索引超出范围

def is_monotone(heights):

    j = 0
    if len(heights) == 0:
        return True
    for i in heights:
        if heights[j + 1] >= heights[j]:
            j += 1

            return True


        return False

Tags: 代码true列表lenreturnifisdef
3条回答

假设return False在for循环之外,否则只有在发送包含1个元素的列表时才会出现错误。你知道吗

问题是,当您发送一个递减列表(或一个包含1个元素的列表)时,您一直在迭代,直到j成为最后一个元素(即len(heights) - 1))的索引,因此当您尝试访问heights[j + 1]时,它会出现IndexError:List index out of range错误。你知道吗

您应该只从0len(heights) - 2进行迭代,您可以使用range函数(在range中,您应该给出len(heights) -1),因为range不包括i时的最后一个元素

示例-

def is_monotone(heights):

    if len(heights) == 0:
        return True
    for j in range(len(heights)-1):
        if heights[j + 1] >= heights[j]:
            return True
    return False

但是,如果函数检查的是列表是否单调递增(所有元素都递增),那么您的逻辑有点不正确,当您发现下一个元素的单个实例大于第一个元素时,不应返回True。你知道吗

相反,当您在连续索引中发现一个数字递减的实例时,应该返回false,而在for循环外返回True。请注意,只有当你的功能是检查数字是否在一个递增的序列。你知道吗

示例-

def is_monotone(heights):

    if len(heights) == 0:
        return True
    for j in range(len(heights)-1):
        if heights[j + 1] < heights[j]:
            return False
    return True

当到达列表末尾时(当您有j = len(heights)-1),索引j+1 = len(list)超出范围,因此引发IndexError异常。你知道吗

但是,即使索引正确,函数也不会告诉您列表是否单调!如果元素1大于元素0,它将返回真值

有一个关于工作职能的命题:

def is_monotone(heights):
    if len(heights) == 0:
        return True
    steps = []
    for j in range(len(heights)-1):
        steps.append(heights[j+1]-heights[j])
    if all(step >= 0 for step in steps) or all(step <= 0 for step in steps):
        return True
    return False

问题来自:

for i in heights:
    if heights[j + 1] >= heights[j]:
        j += 1

当您遍历height时,有时j + 1 = len(height),然后heights[j + 1]超出范围。你知道吗

你应该这样循环:

for i in range(len(heights) - 1):
    if heights[j + 1] >= heights[j]:
        j += 1

正如tobias所指出的,不再需要j,您可以使用i。你知道吗

for i in range(len(heights) - 1):
    if heights[i + 1] >= heights[i]:
        return True

相关问题 更多 >