【问题标题】:List index out of range and i got error in my if block which is inside the while loop列表索引超出范围,我在 while 循环内的 if 块中遇到错误
【发布时间】:2020-03-28 07:50:34
【问题描述】:
def merge(a1,a2):
    if len(a1)<1:
        return a2
    if len(a2)<1:
        return a1
    a1item=a1[0]
    a2item=a2[0]
    i=1
    j=1
    merge=[]
    while(a1item or a2item):
        print(a1item,a2item)
        if a1item<a2item:
            merge.append(a1item)
            a1item=a1[i]
            i+=1
        else:
            merge.append(a2item)
            a2item=a2[j]
            j+=1
        print(merge)


merge([1,2,3],[3,54,100])

我在 a1item=a1[i] 如何在循环指向最后一个元素时停止时出错。 建议我不使用内置函数

【问题讨论】:

  • 您需要检查循环内部。每次i 增加时,您都需要查看它是否超出了其中一个列表的末尾。如果是这样,那之后不要索引到该列表中。
  • @eric 你的陈述是正确的......但与错误或问题无关?
  • 与其他一些编程语言不同,python 不会让您访问不存在的元素。这意味着像 [1,2,3][3] 这样的东西会给你一个错误信息。话虽这么说,while(a1item or a2item): 并不像您期望的那样工作,因为您试图捕捉 a1itema2item 何时变为未定义,这在 python 中永远不会发生。此外,当a1itema2item 为0时,该条件将变为False

标签: python python-3.x if-statement while-loop merge


【解决方案1】:

你需要自己检查你的界限——如果你合并[0,1,2,3][0,4,8],你肯定会发生另一个错误:

while(0 或 0):

falsy 并且你的函数不会进入 while 循环。

用 cmets 修复:

def merge(a1,a2):
    if len(a1)<1:
        return a2
    if len(a2)<1:
        return a1
    i=0
    j=0
    # store result once - micro-optimization
    la1 = len(a1)
    la2 = len(a2)  

    m=[] # do not call variables the same as the function, in case you want to recurse

    # I removed the variables to hold the current values in favor 
    # of directly indexing them
    while True: # beware of (0 or 0) which is falsy
        print(a1[i],a2[j],end=" -> ")
        if a1[i] <= a2[j]:  # one more "true" value in first if branch
            m.append(a1[i]) # if both are same, we take from the 1st list
            i+=1            # no need to branch into the else part
        else:
            m.append(a2[j])
            j+=1
        print(m)

        # stop conditions: if one list is done, add the other to the end of m
        if i == la1:
            m.extend(a2[j:])
            break
        if j == la2:
            m.extend(a1[i:])
            break
    return m


print("----",merge([1,6,9],[0,7,8,11]))

输出:

1 0 -> [0]
1 7 -> [0, 1]
6 7 -> [0, 1, 6]
9 7 -> [0, 1, 6, 7]
9 8 -> [0, 1, 6, 7, 8]
9 11 -> [0, 1, 6, 7, 8, 9]
---- [0, 1, 6, 7, 8, 9, 11]

您可以在此处阅读有关列表切片的更多信息:Understanding slice notation

【讨论】:

  • @Joe 我再次编辑 - 错过了第二个停止条件的休息时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
相关资源
最近更新 更多