Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Created June 23, 2015 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbarkhau/0f60ffc03d0a8c701d47 to your computer and use it in GitHub Desktop.
Save mbarkhau/0f60ffc03d0a8c701d47 to your computer and use it in GitHub Desktop.
unchain.py
import sys
import itertools as it
PY2 = sys.version_info.major == 2
if PY2:
range = xrange
def unchain(elems, chain_size):
"""Reverse of itertools.chain
>>> unchain([1, 2, 3, 4, 5, 6], 3)
[[1, 2, 3], [4, 5, 6]]
"""
for i in range(0, len(elems), chain_size):
yield elems[i:i + chain_size]
test_chained_vals = [1, 2, 3, 4, 5, 6, 7, 8]
test_unchained_vals = [
[1, 2, 3, 4],
[5, 6, 7, 8],
]
assert list(it.chain(*test_unchained_vals)) == test_chained_vals
assert list(unchain(test_chained_vals, 4)) == test_unchained_vals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment