Created
October 18, 2011 15:20
-
-
Save ojii/1295691 to your computer and use it in GitHub Desktop.
Bundle an iterable into a list of tuples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Bundles the iterable `l` into an iterable of tuples of length `x`, filling the last one with `f` if necessary. | |
Examples: | |
In [13]: list(bundle([1,2,3,4,5,6], 3, None)) | |
Out[13]: [(1, 2, 3), (4, 5, 6)] | |
In [14]: list(bundle([1,2,3,4,5,6], 2, None)) | |
Out[14]: [(1, 2), (3, 4), (5, 6)] | |
In [15]: list(bundle([1,2,3,4,5,6], 5, None)) | |
Out[15]: [(1, 2, 3, 4, 5), (6, None, None, None, None)] | |
In [16]: list(bundle(range(9), 5, -12)) | |
Out[16]: [(0, 1, 2, 3, 4), (5, 6, 7, 8, -12)] | |
In [17]: list(bundle('ojii', 3, '?')) | |
Out[17]: [('o', 'j', 'i'), ('i', '?', '?')] | |
""" | |
from itertools import izip_longest | |
bundle = lambda l,x,f:izip_longest(*[l[i::x] for i in range(x)], fillvalue=f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment