Python实现两已知排好序的列表合并成一个排好序的列表

#方法0.5---

lst1 = [1, 3, 7, 9, 12]

lst2 = [4, 8, 9, 13, 15, 19]

def merge(a, b):

    c = []

    h = j = 0

    while j < len(a) and h < len(b):

        if a[j] < b[h]:

            c.append(a[j])

            j += 1

        else:

            c.append(b[h])

            h += 1

    if j == len(a):

        for i in b[h:]:

            c.append(i)

    else:

        for i in a[j:]:

            c.append(i)

    return c


print(merge(lst1, lst2))



#方法一:

lst1 = [1, 3, 7, 9, 12]

lst2 = [4, 8, 9, 13, 15, 19]

lst3 = []

def fun():

    return 1 if len(lst1) > len(lst2) else 0

while lst1 and lst2:

    if lst1[0] < lst2[0]:

        lst3.append(lst1[0])

        lst1.remove(lst1[0])

    else:

        lst3.append(lst2[0])

        lst2.remove(lst2[0])

if fun() == 1:

    lst3.extend(lst1)

else:

    lst3.extend(lst2)

print(lst3)





#方法二


lst1 = [1, 3, 7, 9, 12]

lst2 = [4, 8, 9, 13]

lst3 = []

lst3 = lst1 + lst2

print(lst3)

lst3.sort()

print(lst3)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,199评论 0 2
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 3,365评论 0 3
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 4,151评论 0 2
  • 题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、×、÷四则运算符号。 代码如下: 来源:http:...
    3e1094b2ef7b阅读 231评论 0 0
  • 小女孩大多有公主情结,云云尤其如此。 四岁多的时候,快冬天了,云云和奶奶睡一个被窝。怕她着凉,奶奶每晚都搂着睡。这...
    丑小鸭tyy阅读 1,098评论 0 0

友情链接更多精彩内容