Last active
December 21, 2015 01:39
-
-
Save gyst/6229529 to your computer and use it in GitHub Desktop.
Group a list of items into a nested list of subgroups, where the subgroups are of a certain length.
Useful e.g. if you want to display a flat list into a 2-column or 3-column layout.
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
| #!/usr/bin/python | |
| def groupby(iterable, groupsize=2): | |
| """ | |
| Split an iterable [a, b, c, ...] | |
| into a nested list of tuples [(a, b), (c, ...)] | |
| where the length of the tuples is governed by groupsize. | |
| The default groupsize results in pairwise grouping: | |
| >>> iterable = [1,2,3,4,5,6] | |
| >>> groupby(iterable) | |
| [(1, 2), (3, 4), (5, 6)] | |
| If the number of items in iterable doesn't match the groupsize, | |
| the last returned group is incomplete: | |
| >>> iterable = [1,2,3,4,5] | |
| >>> groupby(iterable) | |
| [(1, 2), (3, 4), (5,)] | |
| We can also group by 3 instead of by 2 items: | |
| >>> iterable = [1,2,3,4,5,6,7] | |
| >>> groupby(iterable, 3) | |
| [(1, 2, 3), (4, 5, 6), (7,)] | |
| """ | |
| result = [] | |
| subgroup = [] | |
| for item in iterable: | |
| subgroup.append(item) | |
| if len(subgroup) % groupsize == 0: | |
| result.append(tuple(subgroup)) | |
| subgroup = [] | |
| if len(subgroup) > 0: | |
| result.append(tuple(subgroup)) | |
| return result | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment