Merging sorted lists/iterators/generators into one stream of values...

Lasse Vågsæther Karlsen lasse at vkarlsen.no
Fri Oct 7 15:56:01 EDT 2005


Lasse Vågsæther Karlsen wrote:
> I need to merge several sources of values into one stream of values. All 
> of the sources are sorted already and I need to retrieve the values from 
<snip>

Ok, after working through the various sources and solutions, here's what 
I finally ended up with:

def merge_sorted(comparison, *sources):
     iterables = []
     for source in sources:
         try:
             source = iter(source)
             iterables.append([source.next(), source])
         except StopIteration:
             pass

     iterables.sort(cmp=comparison, key=lambda x: x[0])
     while iterables:
         yield iterables[0][0]
         try:
             iterables[0][0] = iterables[0][1].next()
             if len(iterables) > 1 and comparison(iterables[0][0], 
iterables[1][0]) > 0:
                 iterables.sort(comparison, key=lambda x: x[0])
         except StopIteration:
             iterables.pop(0)

Thanks to Mike and George for the solutions and pointers.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:lasse at vkarlsen.no
PGP KeyID: 0x2A42A1C2



More information about the Python-list mailing list