1 #!/usr/bin/env python 2 3 "An iterator merging class similar to heapq.merge in Python 2.6." 4 5 from bisect import insort_right 6 7 class itermerge: 8 9 """ 10 Merge ordered sequences to produce an ordered, combined sequence of 11 results. 12 """ 13 14 def __init__(self, sequences): 15 self.iters = [] 16 17 # Prepare the underlying iterators. 18 19 for seq in sequences: 20 it = iter(seq) 21 next = it.next 22 self._add_next(next) 23 24 def sort(self): 25 pass # The output should be sorted. 26 27 def __iter__(self): 28 return self 29 30 def _add_next(self, next): 31 32 """ 33 Store the current value for an iterator, alongside the means of 34 getting the next value: the 'next' method. 35 """ 36 37 try: 38 insort_right(self.iters, (next(), next)) 39 except StopIteration: 40 pass 41 42 def next(self): 43 if self.iters: 44 value, next = self.iters[0] 45 del self.iters[0] 46 self._add_next(next) 47 return value 48 else: 49 raise StopIteration 50 51 # vim: tabstop=4 expandtab shiftwidth=4