列表理解错误“ IndexError:列表索引超出范围”

时间:2019-07-13 16:37:54

标签: python list-comprehension

我正在尝试对以下代码进行列表理解,如果不使用理解功能,则代码可以正常工作。

此代码用于返回数字序列中的缺失数字,该数字序列在给定数字序列的连续项之间具有恒定的差异。

Post Model

使用理解时,我收到一条错误消息。 错误:

def find_missing(sequence):
    difference = min(sequence[1] - sequence[0], sequence[-1] - sequence[-2])
    # for index in range(len(sequence)):
    #     if sequence[index] + difference != sequence[index+1]:
    #         return sequence[index] + difference
    # return [index for index in range(len(sequence))]
    return [sequence[index]+difference for index in range(len(sequence)) if sequence[index]+difference != sequence[index+1]]


print(find_missing([1, 2, 3, 4, 6, 7, 8, 9]))  # ==5
print(find_missing([1, 3, 5, 9, 11]))  # == 7
print(find_missing([1, 3, 4]))  # == 2

1 个答案:

答案 0 :(得分:0)

您会收到错误消息,因为index+1中的sequence[index+1]比上次迭代的数组大一个。 Python通常不鼓励在循环中使用索引-部分是因为创建此类错误非常容易。

如果要比较相邻的元素,则可以在zip(sequence, sequence[1:])上循环。这将为您提供可以比较的货币对-更易于阅读,并且您无需担心索引错误:

def find_missing(sequence):
    difference = min(sequence[1] - sequence[0], sequence[-1] - sequence[-2])

    return [ f + difference 
             for f, n in zip(sequence, sequence[1:]) 
             if  f + difference != n ]


print(find_missing([1, 2, 3, 4, 6, 7, 8, 9]))  # == [5]
print(find_missing([1, 3, 5, 9, 11]))  # == [7]
print(find_missing([1, 3, 4]))  # == [2]