合并两个排序列表。在while循环内完成所有工作

时间:2019-07-11 21:09:44

标签: python sorting

合并两个排序的列表。在while循环内完成所有工作。不要使用扩展。

我可以合并两个排序的列表,但是我不在while循环内做所有工作。

L1 = [ 9, 12, 17, 25 ]
L2 = [ 3, 5, 11, 13, 16 ]



i1 = 0 # index of value in L1 that has not yet been copied.
i2 = 0 # index of value in L2 that has not yet been copied.
L = []

while i1 < len(L1) and i2 < len(L2):
    if L1[i1] < L2[i2]:
        L.append(L1[i1])
        i1 += 1

    else:
        L.append(L2[i2])
        i2 += 1

if i1 == len(L1):
    for val in L2[i2:]:
        L.append(val)
else:
    for val in L1[i1:]:
        L.append(val)

print(L)

预期结果:

[3、5、9、11、12、13、16、17、25]

4 个答案:

答案 0 :(得分:0)

L1 = [ 9, 12, 17, 25 ]
L2 = [ 3, 5, 11, 13, 16 ]



i1 = 0 # index of value in L1 that has not yet been copied.
i2 = 0 # index of value in L2 that has not yet been copied.
L = []

while i1 < len(L1) or i2 < len(L2):
    if i1 == len(L1):
        L.extend(L2[i2:])
        i2 = len(L2)
    elif i2 == len(L2):
        L.extend(L1[i1:])
        i1 = len(L2)
    else:
        if L1[i1] < L2[i2]:
            L.append(L1[i1])
            i1 += 1

        else:
            L.append(L2[i2])
            i2 += 1

print(L)

答案 1 :(得分:0)

不确定是否要简单地完成此操作,但是我只是将所有list1添加到list2,然后使用sort函数对list2进行了排序

user.build_home  # this will work

user.home.build  # this will throw error

答案 2 :(得分:0)

这是我的第一个答案,所以我希望可以。

L1 = [ 9, 12, 17, 25 ]
L2 = [ 3, 5, 11, 13, 16 ]

i1 = 0 # index of value in L1 that has not yet been copied.
i2 = 0 # index of value in L2 that has not yet been copied.
L = []

while i1 < len(L1) or i2 < len(L2):

    if i1 == len(L1) :
        L.extend(L2[i2:])
        break

    if i2 == len(L2) :
        L.extend(L1[i1:])
        break

    if L1[i1] <= L2[i2] :
        L.append(L1[i1])
        i1 += 1

    if L2[i2] < L1[i1] :
        L.append(L2[i2])
        i2 += 1

答案 3 :(得分:0)

如果这不是您必须创建自己的解决方案的家庭作业,那么只需使用Python随附的heapq库:

import heapq

list1 = [ 9, 12, 17, 25 ]
list2 = [ 3, 5, 11, 13, 16 ]
merged = list(heapq.merge(list1, list2))
print(merged)

函数heapq.merge可以合并多个列表,而不仅仅是2个。它假定每个列表都已排序,在这里就是这种情况。返回值是一个生成器,因此我们需要调用list( ... )将该生成器转换为列表。