def groupbykey(iterable, key):
    """
    Create an iterator which returns (key, sub-iterator) grouped by each
    value of key.

    """
    iterator = zip(iterable, key)
    i, value = next(iterator)
    l = [i]
    for i, k in iterator:
        if k == value:
            l.append(i)
            continue
        yield value, l
        value = k
        l = [i]
    if len(l) != 0:
        yield value, l
