Created
June 12, 2019 09:41
-
-
Save hxer/b401fed04159dcb8b77342eaccae4843 to your computer and use it in GitHub Desktop.
可迭代对象按固定大小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
from itertools import islice, chain | |
#!/usr/bin/python3 | |
def batch(iterable, size): | |
source_iter = iter(iterable) | |
while True: | |
batch_iter = islice(source_iter, size) | |
try: | |
first_element = next(batch_iter) | |
except StopIteration: | |
return | |
yield chain([first_element], batch_iter) | |
# In [42]: for r in batch([1,2,3], 2): | |
# ...: print(list(r)) | |
#[1, 2] | |
#[3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment