python group groupe of 2 1

python group groupe of 2

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

Here is what the above code is Doing:
1. We’re using the zip_longest function from the itertools module.
2. We’re passing it the iterable we want to split up into chunks, and the number of chunks we want.
3. We’re also passing it a fillvalue, which is the value we want to use to fill in any missing values.
4. We’re using the asterisk operator to unpack the iterable we want to split up into chunks.
5. We’re passing the result of the zip_longest function to the list function to create a list of tuples.

Similar Posts