[ python-Feature Requests-1757395 ] splice() function for itertools

SourceForge.net noreply at sourceforge.net
Sun Jul 22 18:51:50 CEST 2007


Feature Requests item #1757395, was opened at 2007-07-20 04:12
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1757395&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: Python 2.6
Status: Closed
Resolution: Rejected
Priority: 5
Private: No
Submitted By: Alexander Dutton (asdutton)
Assigned to: Nobody/Anonymous (nobody)
Summary: splice() function for itertools

Initial Comment:
Could we have a splice function in itertools? I see there was once a roundrobin proposal (#756253), but it was three years ago ...

Here's an alternate implementation:

def splice(*args):
  """splice(*iterables) --> iterator
  Returns an iterator whose next() method returns an element from each of the iterables in turn before starting again with the first iterable."""
  iters = list(args)
  n = len(iters)
  i = 0
  while n>0:
    i %= n
    try:
      yield iters[i].next()
      i += 1
    except StopIteration, e:
      n -= 1
      iters[i:i+1] = []
  raise StopIteration

----------------------------------------------------------------------

>Comment By: Raymond Hettinger (rhettinger)
Date: 2007-07-22 11:51

Message:
Logged In: YES 
user_id=80475
Originator: NO

FWIW, here is the optimized recipe:

def roundrobin(*iterables):
    pending = deque(iter(i).next for i in reversed(iterables))
    rotate, pop, _StopIteration = pending.rotate, pending.pop,
StopIteration
    while pending:
        try:
            while 1:
                yield pending[-1]()
                rotate()
        except _StopIteration:
            pop()

----------------------------------------------------------------------

Comment By: Raymond Hettinger (rhettinger)
Date: 2007-07-22 11:19

Message:
Logged In: YES 
user_id=80475
Originator: NO

The reasons for rejecting the roundrobin proposal still apply three years
later.  It is somewhat use case challenged.

FWIW, there is a reasonably efficient pure python implementation using
collections.deque().  See http://docs.python.org/lib/deque-recipes.html for
an unoptimized recipe which can be fine-tuned to use bound methods and all
local variables for better speed.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1757395&group_id=5470


More information about the Python-bugs-list mailing list