Created
March 19, 2014 04:14
-
-
Save carymrobbins/9635336 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| def groups_of(n, xs, **kwargs): | |
| """ | |
| Returns n elements from xs until empty. | |
| Optional 'pad' keyword argument will pad a value to the resulting iterator | |
| to meet | |
| >>> for x in groups_of(2, [1, 2, 3, 4, 5]): | |
| ... print x | |
| [1, 2] | |
| [3, 4] | |
| [5] | |
| >>> for x in groups_of(3, [1, 2, 3, 4, 5], pad=None): | |
| ... print x | |
| [1, 2, 3] | |
| [4, 5, None] | |
| """ | |
| if 'pad' in kwargs: | |
| pad, use_padding = kwargs.pop('pad'), True | |
| else: | |
| pad, use_padding = None, False | |
| xs = iter(xs) | |
| while True: | |
| result = [] | |
| for i in range(n): | |
| try: | |
| result.append(xs.next()) | |
| except StopIteration: | |
| if result: | |
| if use_padding: | |
| result += [pad] * (n - i) | |
| yield result | |
| return | |
| yield result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment