This snippet defines a function to merge sorted iterables containing similar items into a single iterable. Items are supposed to be sorted in ascending order. Only one item per iterable is stored at a time.
# python 2 or 3 """ Author: Written by Gribouillis for the python forum at www.daniweb.com Date: November 15, 2010 License: public domain """ def merged(*iterables): """Merge a sequence of sorted iterables into a single iterable. contract: * each iterable argument is sorted in ascending order. * the returned iterable is sorted in ascending order """ import sys if sys.version_info < (3,): import Queue as queue else: import queue iterables = [iter(it) for it in iterables] heap = queue.PriorityQueue(len(iterables)) for n, it in enumerate(iterables): try: heap.put((next(it), n), block = False) except StopIteration: pass try: while True: item, n = heap.get(block = False) heap.task_done() yield item try: heap.put((next(iterables[n]), n)) except StopIteration: pass except queue.Empty: raise StopIteration if __name__ == "__main__": from random import random from pprint import pprint L = [ sorted(random() for i in range(n)) for n in (10, 5, 15) ] pprint(L) pprint(list(merged(*L)))
About the Author