我一直在尝试用Python编写合并排序程序:
0 4 1 4 9 8 0 7 6 8 3 4 7 2 3 1 7 3 1 2 4 0 8 6 7
但是当我执行这段代码时
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
我收到错误:
print merge([43, 60], [71, 84])
为什么我会这样做?
答案 0 :(得分:0)
问题在于list1
。您继续从第13行del list1[0]
的list1中删除项目,当list1
为空时,您尝试在第11行(list1[0]
)上使用if (list1[0]<list2[0]) :
访问该项目。列表中没有任何内容,因此Python会抛出错误
indexError:列表索引超出范围