【问题标题】:Merging two sorted lists into a larger sorted list将两个排序列表合并成一个更大的排序列表
【发布时间】: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) &gt; 0)。第一个列表中的元素用完了,但第二个列表中仍有元素。
  • 另外,不要使用&amp;(这是按位与),使用and。但不是在这里。使用or。不过,这仍然行不通。

标签: python sorting


【解决方案1】:

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

import heapq

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

【讨论】:

  • 如果您希望标准库完成所有工作,您不妨致电sorted。
【解决方案2】:

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

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])

【讨论】:

    【解决方案3】:

    即使列表中的元素不足,也要确保继续添加元素。一旦aList 或bList 为空,您当前的代码就会停止,这可能不是您想要的。

    您可以通过使用if 表达式将空列表评估为False 的事实来做到这一点:

    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]                                                                             
    []                                                                                                   
    []   
    

    【讨论】:

      【解决方案4】:

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

      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
      

      【讨论】:

        【解决方案5】:

        这个替代方案遵循@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))
        

        【讨论】:

          猜你喜欢
          • 2011-09-26
          • 2013-11-10
          • 1970-01-01
          • 2015-05-12
          • 1970-01-01
          • 2023-02-18
          • 1970-01-01
          • 2022-10-05
          • 2018-04-17
          相关资源
          最近更新 更多