python:“while(len(list1)> 0)或(len(list2)> 0)”不起作用

时间:2016-08-08 05:19:15

标签: python

我参加了Google Python课程,我正在解决以下问题:

  

鉴于两个列表按递增顺序排序,请按排序顺序创建并返回所有元素的合并>列表。您可以修改传入的>列表。理想情况下,解决方案应该在“线性”时间内工作,对两个列表进行单次>传递。

我的解决方案如下:

def linear_merge(list1, list2):
    # +++your code here+++
    a = []
    while (len(list1)>0) or (len(list2)>0):
        if list1[-1] > list2[-1]:
            a.append(list1.pop(-1))
        elif list1[-1] < list2[-1]:
            a.append(list2.pop(-1))
        else:
            a.append(list1.pop(-1))
            a.append(list2.pop(-1))
     #Have to force check
        if (len(list1)==0):
            break
        if (len(list2)==0):
            break
    if len(list1)>0:
        res = (a+list1)
        return res[::-1]
    else:
        res = (a+list2)
        return res[::-1]

我的问题是,即使我检查两个列表是否为空,我得到列表索引超出范围错误。我必须强制检查while循环结束时是否有任何列表为空,以防止发生错误。

为什么while循环无法正确看到其中一个列表为空?我是python的新手,我正在寻找一些关于为什么会发生这种情况的澄清。

1 个答案:

答案 0 :(得分:1)

  

我的问题是即使我检查两个列表是否都是空的......

不,您正在检查其中任何一个是否为空

改变这个:

while (len(list1)>0) or (len(list2)>0)

对此:

while (len(list1)>0) and (len(list2)>0)

while循环结束时继续处理一个仍然不为空的列表。