Created
July 29, 2016 00:30
-
-
Save dmyersturnbull/e42120b7f0776f968f9807355f28ed95 to your computer and use it in GitHub Desktop.
Zip function that requires the same lengths (and still works with generators).
This file contains hidden or 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
| def zip_strict(*args): | |
| """Same as zip(), but raises a ValueError if the lengths don't match.""" | |
| iters = [iter(axis) for axis in args] | |
| n_elements = 0 | |
| failures = [] | |
| while len(failures) == 0: | |
| n_elements += 1 | |
| values = [] | |
| failures = [] | |
| for axis, iterator in enumerate(iters): | |
| try: | |
| values.append(next(iterator)) | |
| except StopIteration: | |
| failures.append(axis) | |
| if len(failures) == 0: | |
| yield tuple(values) | |
| if len(failures) == 1: | |
| raise ValueError("Too few elements ({}) along axis {}".format(n_elements, failures[0])) | |
| elif len(failures) < len(iters): | |
| raise ValueError("Too few elements ({}) along axes {}".format(n_elements, failures)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment