您的位置:首页 > 编程语言 > Python开发

Python 合并多个有序序列

2012-12-30 16:05 260 查看
# -*- coding: utf-8 -*-
def merge(*sequences):
import heapq
heap = [(seq[0],seq) for seq in sequences]
heapq.heapify(heap)
while heap:
x, seq =  heapq.heappop(heap)
yield seq.pop(0)
if seq:
heapq.heappush(heap, (seq[0], seq))

A = [[1,2,3,4], [5,6,8], [1,3,5,6,7,9]]
print list(merge(*A))
# >>> [1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 9]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: