Skip to content

Instantly share code, notes, and snippets.

@hxer
Created June 12, 2019 09:41
Show Gist options
  • Save hxer/b401fed04159dcb8b77342eaccae4843 to your computer and use it in GitHub Desktop.
Save hxer/b401fed04159dcb8b77342eaccae4843 to your computer and use it in GitHub Desktop.
可迭代对象按固定大小chunk分割,不补齐
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