Split iterator into multiple streams

Paul Rubin no.email at nospam.invalid
Sat Nov 6 05:31:03 EDT 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> def split(iterable, n):
>     iterators = []
>     for i, iterator in enumerate(itertools.tee(iterable, n)):
>         f = lambda it, i=i: (t[i] for t in it)
>         iterators.append(f(iterator))
>     return tuple(iterators)
>
> Is this the right approach, or have I missed something obvious?

I think there is no way around using tee.  But the for loop looks ugly.
This looks more direct to me, if I didn't mess something up:

def split(iterable, n):
   return tuple(imap(itemgetter(i),t) for i,t in enumerate(tee(iterable,n)))



More information about the Python-list mailing list