python实现把两个排好序的列表合并成一个排好序的列表

一:方法1
#将两个排好序的列表合并成一个排好序的列表
def merge_list(a,b):
    if not a:
        return b
    if not b:
        return a
    a_index = b_index = 0
    ret = list()
    while a_index < len(a) and b_index < len(b):
        if a[a_index] <= b[b_index]:
            ret.append(a[a_index])
            a_index += 1
        else:
            ret.append(b[b_index])
            b_index += 1
    if a_index < len(a):
        ret.extend(a[a_index:])
    if b_index < len(b):
        ret.extend(b[b_index:])
    return ret
if __name__ == "__main__":

    #组合小文件
    lt1 = [1,8,12,13]
    lt2 = [5,8,17,28]
    lt3 = [1,90,98,99,100]
    res = merge_list(lt1,lt2)
    res1 = merge_list(res,lt3)
    print(res)
    print(res1)

#########################################结果

[1, 5, 8, 8, 12, 13, 17, 28]
[1, 1, 5, 8, 8, 12, 13, 17, 28, 90, 98, 99, 100]

如果是多个待排序的列表,采用方法二较好,借助reduce()函数

二:方法2

from functools import reduce
lts = list()
lts.append(lt1)
lts.append(lt2)
lts.append(lt3)
res2 = reduce(merge_list,lts)
print(res2)

猜你喜欢

转载自blog.csdn.net/qq_38839677/article/details/81532536