iterblocks cookbook example

Steve Howell showell30 at yahoo.com
Sat Jun 2 13:19:43 EDT 2007


George Sakkis produced the following cookbook recipe,
which addresses a common problem that comes up on this
mailing list:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877


I would propose adding something like this to the
cookbook example above.

def iterblocks2(lst, start_delim):
    # This variation on iterblocks shows a more
typical
    # implementation that behaves like iterblocks for
    # the Hello World example.  The problem with this
naive
    # implementation is that you cannot pass arbitrary
    # iterators.
    blocks = []
    new_block = []
    for item in lst:
        if start_delim(item):
            if new_block: blocks.append(new_block)
            new_block = []
        else:
            new_block.append(item)
    if new_block: blocks.append(new_block)
    return blocks

Comments welcome.  This has been tested on George's
slow-version-of-string-split example.  It treates the
delimiter as not being part of the block, and it punts
on the issue of what to do when you have empty blocks
(i.e. consecutive delimiters).






       
____________________________________________________________________________________
Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. 
http://answers.yahoo.com/dir/?link=list&sid=396545433



More information about the Python-list mailing list