Python:组合两个排序列表(并保持排序),而不使用内置排序

时间:2015-10-04 23:12:30

标签: python sorting merge

我在网上找到了这个合并排序解决方案,我想知道while循环是否可行,或者是否还有一种方法可以使用2 for循环并进行比较。

def merge(l, m):
    result = []
    i = j = 0
    total = len(l) + len(m)
    while len(result) != total:
        if len(l) == i:
            result += m[j:]
            break
        elif len(m) == j:
            result += l[i:]
            break
        elif l[i] < m[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(m[j])
            j += 1
    print result
合并([1,2,6,7],[1,3,5,9])

4 个答案:

答案 0 :(得分:2)

Python的内置sorted实际上非常有效(因为它使用的TimSort利用了列表子集中的现有排序)。也就是说,有一个内置功能可以避免甚至构建一个新的list sorted(或您的解决方案):heapq.merge

它专为您拥有每个独立排序的现有列表的场景而设计。它是一个生成器函数,因此根本不需要创建新的list。如果您正在尝试这样做以学习,请享受自己,但如果这是“真正的”代码,请使用附带的电池并避免重新发明轮子。

答案 1 :(得分:1)

您可以轻松地更改为:

def merge_for(l,m):
    result = []
    i = j = 0
    total = len(l) + len(m)

    for k in range(total):

        if len(l) == i:
            result += m[j:]
            print("append el {} at index {}".format(m[j], k))

            break
        elif len(m) == j:
            result += l[i:]
            break
        elif l[i] < m[j]:
            result.append(l[i])
            print("append el {} at index {}".format(l[i], k))
            i += 1
        else:
            result.append(m[j])
            print("append el {} at index {}".format(m[j], k))
            j += 1

    print(result)


print(merge_for([1,2,6,7], [1,3,5,9]))

append el 1 at index 0
append el 1 at index 1
append el 2 at index 2
append el 3 at index 3
append el 5 at index 4
append el 6 at index 5
append el 7 at index 6
append el 9 at index 7

[1, 1, 2, 3, 5, 6, 7, 9]

答案 2 :(得分:0)

使用发电机的解决方案:

from itertools import chain
def merge(l1,l2):
    i,j = 0,0
    try:
        while True:
            if l1[i] < l2[j]:
                yield l1[i]
                i +=1
            else:
                yield l2[j]
                j+=1
    except IndexError:
        for e in chain(l1[i:],l2[j:]):
            yield e

[x for x in merge([1,2,6,7], [1,3,5,9])]
  

[1,1,2,3,5,6,7,9]

答案 3 :(得分:0)

如果您有一个排序列表,则bisect.insort另一个:

from bisect import insort

a,b = [1,2,6,7], [1,3,5,9]

for ele in b:
    insort(a, ele)
print(a)
[1, 1, 2, 3, 5, 6, 7, 9]
相关问题