def grouped(sequence, key=None, transform=None):
    """
    Parse the sequence into groups, according to key:

        >>> ret = grouped(range(10), lambda n: n % 3)
        >>> ret[0]
        [0, 3, 6, 9]
        >>> ret[1]
        [1, 4, 7]
        >>> ret[2]
        [2, 5, 8]
    """
    groups = {}
    if not key:
        key = lambda x: x
    if not transform:
        transform = lambda x: x
    for item in sequence:
        groups.setdefault(key(item), []).append(transform(item))
    return groups