-
-
Save jmhobbs/1184356 to your computer and use it in GitHub Desktop.
Get Python list in chunks
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/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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thinner version :-)