将两个已排序的列表合并为一个更大的排序列表

时间:2015-01-30 22:50:17

标签: python sorting

我试图制作一个合并功能,用于我正在制作的合并排序。

我遇到了一些麻烦,我似乎无法找到错误。

我评论它试图向你们展示我的思考过程:

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。有人有想法吗?

5 个答案:

答案 0 :(得分:5)

这是一个使用Python库heapq的版本:

import heapq

def merge(aList, bList)
    return list(heapq.merge(aList, bList))

答案 1 :(得分:3)

这不是最优雅的解决方案,但它确实显示了所有可能的条件并解决了手头的问题,应该有助于理解合并操作的逻辑。

def merge(a, b):
   newList = []
   while(len(a) > 0 or len(b) > 0):
      if( len(a) == 0 ):
         newList.append(b[0])
         b.pop(0)
      elif( len(b) == 0 ):
        newList.append(a[0])
         a.pop(0)
      elif( a[0] < b[0] ):
         newList.append(a[0])
         a.pop(0)
      else:
         newList.append(b[0])
         b.pop(0)
return newList

>>> merge([3,4,8,9], [1,2,5,8])

答案 2 :(得分:1)

即使列表中没有元素,也要确保继续添加元素。当aListbList为空时,您当前的代码会停止,这可能不是您想要的。

您可以使用False表达式将空列表评估为if这一事实来实现此目的:

def merge(aList, bList):
    newList = []
    while (aList or bList): # single empty list won't stop the loop
        if not bList or (aList and aList[0] < bList[0]):
            # either bList is empty, or aList has next item
            newList.append(aList.pop(0))
        else:
            # bList has next item
            newList.append(bList.pop(0))
    reutrn newList

list1 = [3, 4, 8, 9]
list2 = [1, 2, 5, 8]

print(merge(list1, list2))
print(list1)
print(list2)

输出:

sh-4.2# python3 main.py                                                                              
[1, 2, 3, 4, 5, 8, 8, 9]                                                                             
[]                                                                                                   
[]   

答案 3 :(得分:0)

不是最好的解决方案,但我今天遇到了同样的问题;

def merge(str1, str2):
j = 0
for i in range(len(str2)):
    while(j < len(str1) and str2[i] > str1[j]):
        j += 1
    str1.insert(j, str2[i])
return str1

答案 4 :(得分:0)

此替代方法遵循@Reut Sharabani关于处理空列表的想法,但我只是决定弹出最小的数字,直到清空任何人,然后将另一个(剩余的)添加到末尾。

def merge_sorted_lists(list1,list2):
    new_sorted = []

    # select the smallest number in current lists until empty any list
    while len(list1 and list2):    
        toadd = list1.pop(0) if (list1[0]<=list2[0])  else list2.pop(0) # select the smaller number
        new_sorted.append(toadd)

    remaining = list1 if (not list2) else list2
    new_sorted += remaining # the remaining is always greater and sorted
    return new_sorted

list1, list2 = [35, 36, 46, 82, 92], [0, 11, 15, 22, 22, 33, 35, 53, 59, 61, 74, 76]
print(merge_sorted_lists(list1,list2))