Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This could be improved.
- def chunker(iterable, num):
- """
- Returns an generator which yields the available chunks.
- If the last chunk is incomplete, it'll be cut off.
- """
- iterator = iter(iterable)
- while iterator:
- ret = []
- for _ in range(num):
- try:
- ret.append(next(iterator))
- except StopIteration:
- return
- else:
- yield ret
- # hint from #python: use itertools
- # credits to: KirkMcDonald
- num = 2
- iterable = [1,2,3,4]
- list(itertools.zip(*[iter(iterable)] * 2)) # no elements will lost
- list(zip(*[iter(iterable)] * num)) # last incomplete chunks will be lost
- #as function
- def chunker_builtin(zip_function, length, iterable):
- return zip_function(*[iter(iterable)] * length)
- # chunker_builtin(itertools.zip_longest, 2, iterable) -> returns an generator
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement