Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

join function for iterutils #43

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions boltons/iterutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,54 @@ def one(src, cmp=None):
return False
the_one = i
return the_one

def join(iters, key=lambda x: x):
"""
Description
===========
Iteration utility to join two or more iterators
sorted on a common key, very much like sql outer
join

Parameters
==========
iters: a list of two or more iterators sorted over
the provided key function
key: a function that returns the key to join on,
and defaults to the identity function

Returns
=======
The outer join of two or more iterators

Examples
========
>>> list(join([range(5),range(2,7),range(6,9)]))
[(0, None, None), (1, None, None), (2, 2, None), (3, 3, None), (4, 4, None), (None, 5, None), (None, 6, 6), (None, None, 7), (None, None, 8)]
"""

try:
iters = [iter(i) for i in iters]
except:
raise TypeError('expected an iterable of iterables')
if not callable(key):
raise TypeError('expected callable key function')

vals = [None] * len(iters)
least = None

while True:
for i in xrange(len(vals)):
try:
if least == vals[i]:
vals[i] = next(iters[i])
except StopIteration:
vals[i] = None

if all((v == None) for v in vals): break

least = min(key(v) for v in vals if (v != None))
rec = tuple((v if (key(v) == least) else None) for v in vals)

yield rec

26 changes: 26 additions & 0 deletions tests/test_iterutils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-

import sys

from boltons.iterutils import join

def test_join():
joined = [(0, 0, None),
(1, 1, None),
(2, 2, None),
(3, 3, None),
(4, None, None),
(5, None, 5),
(6, None, 6),
(7, None, 7),
(8, None, 8),
(9, None, 9),
(None, None, 10),
(None, None, 11),
(None, None, 12),
(None, None, 13),
(None, None, 14)]

assert list(join([range(10),range(4),range(5,15)])) == joined