Skip to content

Instantly share code, notes, and snippets.

@jmhobbs
Forked from squarepegsys/chunker.py
Created August 31, 2011 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmhobbs/1184356 to your computer and use it in GitHub Desktop.
Save jmhobbs/1184356 to your computer and use it in GitHub Desktop.
Get Python list in chunks
#!/usr/bin/env python
import unittest
from itertools import cycle
## get a list in chunks
## if we run out of items in the list, start again from the beginning
class Chunker(object):
def __init__(self,flist,chunk_size):
self.chunk_size = chunk_size
self.iterator = cycle( flist )
def next(self):
return [self.iterator.next() for i in range(self.chunk_size)]
class TestChunker(unittest.TestCase):
def test_get_list(self):
lst = range(10)
c = Chunker(lst,7)
self.assertEquals(range(7),c.next())
def test_get_rollover(self):
lst = range(10)
c = Chunker(lst,7)
self.assertEquals(range(7),c.next())
next = c.next()
self.assertEquals(7,len(next))
self.assertEquals([7,8,9,0,1,2,3],next)
self.assertEquals([4,5,6,7,8,9,0],c.next())
if __name__=='__main__':
unittest.main()
@jmhobbs
Copy link
Author

jmhobbs commented Aug 31, 2011

Thinner version :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment