Created
September 10, 2011 15:37
-
-
Save durden/1208443 to your computer and use it in GitHub Desktop.
Iterate of a list chunk by chunk
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
class ListChunk: | |
def __init__(self, items, chunksize): | |
self.items = items | |
self.chunksize = chunksize | |
self.ii = 0 | |
def __iter__(self): | |
return self | |
def next(self): | |
if self.ii >= len(self.items): | |
raise StopIteration | |
tmp = self.items[self.ii:self.ii + self.chunksize] | |
self.ii = self.ii + self.chunksize | |
return tmp | |
items = ListChunk([1,2,3,4,5,5,6,7,8], 2) | |
for slice in items: | |
print slice |
Here's my take:
class IterChunk(object):
def __init__(self, items, chunksize):
self.items = items
self.chunksize = chunksize
self._i = 0
def __iter__(self):
return self
def next(self):
slice = self.items[self._i:(self._i + self.chunksize)]
self._i += self.chunksize
if slice:
return slice
raise StopIteration
I wouldn't be surprised if there was something in itertools that does this though.
Really the easiest thing to do is just write a generator:
def chunk(l, chunksize):
for i in range(0, len(l), chunksize):
yield l[i:i+chunksize]
>>> items = chunk([1,2,3,4,5,5,6,7,8], 2)
>>> for item in items:
... print item
[1, 2]
[3, 4]
[5, 5]
[6, 7]
[8]
Nice, the generator solution is way better!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just playing around with custom iterators, etc. It seems like a lot of code to just loop over a list of items by chunking them up. Is there a shorter way to do this?