[Python-ideas] zip_strict() or similar in itertools ?

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Apr 4 15:15:55 CEST 2013


Wolfgang Maier <wolfgang.maier at ...> writes:

Turns out that Peter's solution (using a class instance as the marker, and
managing to get away with a test for it only once after exhaustion of the
iterator) is impressively fast indeed:

def strict_grouper(items, size, strict):
    fillvalue = object()
    args = [iter(items)]*size
    chunks = zip_longest(*args, fillvalue=fillvalue)
    prev = next(chunks)

    for chunk in chunks:
        print (prev)
        yield prev
        prev = chunk

    if prev[-1] is fillvalue:
        if strict:
            raise ValueError
        else:
            while prev[-1] is fillvalue:
                prev = prev[:-1]

    yield prev

beats my old, clumsy approach by a speed factor of ~5, i.e., it's less than
a factor 2 slower than the grouper() recipe, but raises the error I wanted!
Certainly good enough for me, and, yes, I think it would make a nice
itertools recipe.

Thanks for your help,
Wolfgang








More information about the Python-ideas mailing list