【发布时间】:2015-01-30 22:50:17
【问题描述】:
我正在尝试创建一个将在我正在创建的合并排序中使用的合并函数。
我遇到了一些麻烦,我似乎找不到错误。
我评论它是为了向你们展示我的思考过程:
def merge(aList, bList):
newList = []
while (len(aList) > 0) & (len(bList) > 0): #Loop until both lists are empty
if aList[0] < bList[0]: #If the first item of aList is smaller than the first item of bList
newList.append(aList[0]) #add that item to the new list
aList.pop(0) #and remove it from the original list
else: #If it gets here, that means the first item of bList was smaller
newList.append(bList[0]) #So put the first item of bList is the new list
bList.pop(0) #and remove it from the original
return newList
list1 = [3, 4, 8, 9]
list2 = [1, 2, 5, 8]
print(merge(list1, list2))
print(list1)
print(list2)
输出:
[1, 2, 3, 4, 5, 8]
[8, 9]
[0]
我原以为 list1 和 list2 为空,但由于某种原因,list1 中似乎有一个未放置的 8 和 9。有人有想法吗?
【问题讨论】:
-
因为
while (len(aList) > 0)。第一个列表中的元素用完了,但第二个列表中仍有元素。 -
另外,不要使用
&(这是按位与),使用and。但不是在这里。使用or。不过,这仍然行不通。