超出范围。如何将列表的其余部分添加到累加器?

Out of range. How to add the remainder of list to accumulator?

我得到 [-7,-4,-2],但我想将剩余的数字添加到我的累加器,但我在第二个 if 语句中一直超出范围。我将如何继续添加剩余列表? 输入:交错([-7, -2, -1], [-4, 0, 4, 8])

def interleaved(seq1,seq2):
i = 0
j = 0
res = []

    

while i <len(seq1) and j <len(seq2):
    if seq1[i] < seq2[j]:
        res.append(seq1[i])
        i+=1
    if  seq2[j] <= seq1[i]:
        res.append(seq2[j])
        j+=1
return res

添加了一个 if 语句来检查我们是否“完成”了对 seq1 的探索(相同的 if “检查”可以应用于 seq2 以防万一负值多于 seq1)

def interleaved(seq1, seq2):
    i = 0
    j = 0
    res = []

    while i < len(seq1) and j < len(seq2):
        if seq1[i] < seq2[j]:
            res.append(seq1[i])
            i += 1
            if i == len(seq1):  # If we explored all of seq1 (reached the end)
                for num in seq2[j:]:  # Explore the rest of seq2
                    res.append(num)  # Append the rest
                break  # Break the while loop and go to "return"
        if seq2[j] <= seq1[i]:
            res.append(seq2[j])
            j += 1

    return res

print(interleaved())