Skip to content

Instantly share code, notes, and snippets.

@troolee
Created May 5, 2011 20:18
Show Gist options
  • Save troolee/957832 to your computer and use it in GitHub Desktop.
Save troolee/957832 to your computer and use it in GitHub Desktop.
split_on_packets
def split_on_packets(iterable, packet_size):
'''
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> list(split_on_packets(a, 3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
>>> list(split_on_packets(a, 13))
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
>>> list(split_on_packets(a, 1))
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]]
'''
assert(hasattr(iterable, '__iter__'))
assert(packet_size > 0)
iter = iterable.__iter__()
while True:
packet = []
try:
for i in xrange(packet_size):
packet.append(iter.next())
yield packet
except StopIteration:
if packet:
yield packet
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment