Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created February 26, 2014 05:18
Show Gist options
  • Save podhmo/9223923 to your computer and use it in GitHub Desktop.
Save podhmo/9223923 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
import sys
class Sample(object):
def __init__(self, n):
self.n = n
def __iter__(self):
for i in range(self.n):
print(i)
yield i
def __len__(self):
return self.n
def chunk(xs, n):
xs = list(xs)
for i in range(0,len(xs), n):
yield(xs[i:i+n])
def chunk2(xs, n):
itr = iter(xs)
r = xrange(n)
while True:
yield [next(itr) for i in r]
itr = chunk(Sample(10), 2)
print("よくあるchunk")
print(next(itr))
print(next(itr))
print(next(itr))
print("-")
for e in itr:
print(e)
print("@@@@@@@@@@")
itr = chunk2(Sample(10), 2)
print(next(itr))
print(next(itr))
print(next(itr))
print("-")
for e in itr:
print(e)
@podhmo
Copy link
Author

podhmo commented Feb 26, 2014

よくあるchunk
0
1
2
3
4
5
6
7
8
9
[0, 1]
[2, 3]
[4, 5]
-
[6, 7]
[8, 9]
@@@@@@@@@@
0
1
[0, 1]
2
3
[2, 3]
4
5
[4, 5]
-
6
7
[6, 7]
8
9
[8, 9]

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