Last active
August 29, 2015 14:18
-
-
Save denhartog/0fa856acf7dee8ac1911 to your computer and use it in GitHub Desktop.
grouper
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
from itertools import zip_longest, islice | |
def grouper(iterable, n): | |
return zip(*[iter(iterable)] * n) | |
def grouper_longest(iterable, n, fillvalue=None): | |
return zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue) | |
i0 = [] | |
i1 = [1] | |
i2 = [1,2,3,4] | |
i3 = [1,2,3,4,5] | |
i4 = [1,2,3,4,5,6,7,8] | |
i5 = [1,2,3,4,5,6,7,8,9] | |
i6 = [1,2,3,4,5,6,7,8,9,10,11,12] | |
for g in islice(grouper(i0, 4), 2): | |
print(g) | |
for g in islice(grouper(i1, 4), 2): | |
print(g) | |
for g in islice(grouper(i2, 4), 2): | |
print(g) | |
for g in islice(grouper(i3, 4), 2): | |
print(g) | |
for g in islice(grouper(i4, 4), 2): | |
print(g) | |
for g in islice(grouper(i5, 4), 2): | |
print(g) | |
for g in islice(grouper(i6, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i0, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i1, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i2, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i3, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i4, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i5, 4), 2): | |
print(g) | |
for g in islice(grouper_longest(i6, 4), 2): | |
print(g) | |
def group_walk(iterable, group_size): | |
"""Yields len(iterable) - group_size + 1 groups of group_size from iterable | |
EXAMPLE: | |
>>> iterable = [1,2,3,4] | |
>>> for group in group_walk(iterable, 2): | |
... print(group) | |
... | |
[1, 2] | |
[2, 3] | |
[3, 4] | |
>>> | |
NOTES: | |
group_walk() will yield NOTHING if: | |
len(iterable) < 2; or | |
group_size < 2; just use standard iteration if you want "groups" of one! | |
TODO: | |
if 2 > group_size | len(iterable): | |
raise ValueError | |
""" | |
for i in range(len(iterable[:1 - group_size])): | |
yield iterable[i:i + group_size] | |
#none | |
l = [] | |
group_walk(l) | |
#1 | |
l = [(2012, 3)] | |
group_walk(l) | |
#2 | |
l = [(2012, 3), (2012, 4)] | |
group_walk(l) | |
#3 | |
l = [(2012, 3), (2012, 4), (2013, 1)] | |
group_walk(l) | |
#4 | |
l = [(2012, 3),(2012, 4),(2013, 1),(2013, 2)] | |
group_walk(l) | |
#5 | |
l = [(2012, 3), (2012, 4), (2013, 1), (2013, 2), (2013, 3)] | |
group_walk(l) | |
#10 | |
l = [(2012, 3), (2012, 4), (2013, 1), (2013, 2), (2013, 3), (2013, 4), (2014, 1), (2014, 2), (2014, 3), (2014, 4)] | |
group_walk(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment