Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的合并排序程序出现错误?_Python_Python 2.7 - Fatal编程技术网

Python 为什么我的合并排序程序出现错误?

Python 为什么我的合并排序程序出现错误?,python,python-2.7,Python,Python 2.7,我一直在尝试用Python编写一个合并排序程序: def merge (list1 , list2) : result = [] while (len(list1) != 0 or len(list2) != 0) : if (len(list1) == 1 and len(list2) == 0) : result.append(list1[0]) del list1[0] elif (len(

我一直在尝试用Python编写一个合并排序程序:

def merge (list1 , list2) : 
    result = []
    while (len(list1) != 0 or len(list2) != 0) : 
        if (len(list1) == 1 and len(list2) == 0) :
            result.append(list1[0])
            del list1[0]
        elif (len(list1) == 0 and len(list2) == 1) :
            result.append(list2[0])
            del list2[0]
        else :
            if (list1[0]<list2[0]) : 
                result.append(list1[0])
                del list1[0]
            elif (list1[0]>list2[0]) : 
                result.append(list2[0])
                del list2[0]

    return result
我得到一个错误:

Traceback (most recent call last):
  File "mergesort.py", line 99, in <module>
    print merge([43, 60], [71, 84])
  File "mergesort.py", line 11, in merge
    if (list1[0]<list2[0]) :
IndexError: list index out of range
回溯(最近一次呼叫最后一次):
文件“mergesort.py”,第99行,在
打印合并([43,60],[71,84])
文件“mergesort.py”,第11行,在merge中

如果(list1[0]您已经迭代,直到
list1
为空,并已将两个元素移动到
result
。在问题点使用简单跟踪

    else :
        print "TRACE", list1, list2, result
        if (list1[0]<list2[0]) : 
            result.append(list1[0])
            del list1[0]
其他:
打印“跟踪”,列表1,列表2,结果

如果(list1[0]问题在于
list1
。您不断从第13行的列表1中删除项目
del list1[0]
,当
list1
为空时,您尝试使用第11行的
list1[0]
访问它(
if(list1[0]正如上面所说的,因为列表索引超出范围。此外,您的代码正在运行,您的意思是询问为什么会出现错误。调试的一个好方法是在方法周围添加大量日志,以提供您怀疑可能存在问题的状态。例如,错误消息中提到的行之前。
    else :
        print "TRACE", list1, list2, result
        if (list1[0]<list2[0]) : 
            result.append(list1[0])
            del list1[0]
TRACE [43, 60] [71, 84] []
TRACE [60] [71, 84] [43]
TRACE [] [71, 84] [43, 60]
Traceback (most recent call last):
  File "so.py", line 21, in <module>
    print merge([43, 60], [71, 84])
  File "so.py", line 12, in merge
    if (list1[0]<list2[0]) : 
IndexError: list index out of range