我正在尝试制作一个合并函数,该函数将用于我正在制作的归并排序中。
我遇到了一些麻烦,似乎找不到错误。
我已经进行了注释,以便向大家展示我的思考过程:
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)
,第一个列表已经用尽了元素,但第二个列表中仍有元素。 - L3viathan&
(这是按位与),请使用and
。但不是在这里。使用or
。然而,那仍然不起作用。 - L3viathan