

def group(iterable, num, predicate=None):
    "Combines the elements produced by the given iterable so that every `n`\n    items are returned as a tuple.\n\n    >>> items = [1, 2, 3, 4]\n    >>> for item in group(items, 2):\n    ...     print(item)\n    (1, 2)\n    (3, 4)\n\n    The last tuple is padded with `None` values if its' length is smaller than\n    `num`.\n\n    >>> items = [1, 2, 3, 4, 5]\n    >>> for item in group(items, 2):\n    ...     print(item)\n    (1, 2)\n    (3, 4)\n    (5, None)\n\n    The optional `predicate` parameter can be used to flag elements that should\n    not be packed together with other items. Only those elements where the\n    predicate function returns True are grouped with other elements, otherwise\n    they are returned as a tuple of length 1:\n\n    >>> items = [1, 2, 3, 4]\n    >>> for item in group(items, 2, lambda x: x != 3):\n    ...     print(item)\n    (1, 2)\n    (3,)\n    (4, None)\n    "
    buf = []
    for item in iterable:
        flush = (predicate and (not predicate(item)))
        if (buf and flush):
            buf += ([None] * (num - len(buf)))
            (yield tuple(buf))
            del buf[:]
        buf.append(item)
        if (flush or (len(buf) == num)):
            (yield tuple(buf))
            del buf[:]
    if buf:
        buf += ([None] * (num - len(buf)))
        (yield tuple(buf))

dataset/ETHPy150Open edgewall/trac/trac/util/presentation.py group/original