Created
July 13, 2018 00:18
-
-
Save mattwigway/26bf5bf0fdb7a7f55da0f2b4fcd0e587 to your computer and use it in GitHub Desktop.
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
# similar to Python's built in zip function, but yielding named tuples instead of tuples. | |
# i.e. list(namedzip(a=[1, 2], b=[3, 4])) => [namedzipitem(a=1, b=3), namedzipitem(a=2, b=4)] | |
# Author: Matthew Wigginton Conway <mwconway@asu.edu> | |
# feel free to use and share | |
from collections import namedtuple | |
def namedzip (**kwargs): | |
keys = list(kwargs.keys()) | |
typ = namedtuple('namedzipitem', keys) | |
length = len(kwargs[keys[0]]) | |
if not all([len(kwargs[key]) == length for key in keys[1:]]): | |
raise IndexError('lengths much match') | |
for i in range(length): | |
yield typ(**{ key: kwargs[key][i] for key in keys }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment