Created
June 23, 2015 16:41
-
-
Save mbarkhau/0f60ffc03d0a8c701d47 to your computer and use it in GitHub Desktop.
unchain.py
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
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