Created
April 24, 2015 14:07
-
-
Save zagorulkinde/41087247d6b800fbbc57 to your computer and use it in GitHub Desktop.
Python lazy zip gen
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_gen(list_key, list_value): | |
''' | |
>>> dict([(a,b) for (a,b) in zip_gen([1,2,3,4], ['a','b','c','d'])]) | |
{1: 'a', 2: 'b', 3: 'c', 4: 'd'} | |
>>> dict([(a,b) for (a,b) in zip_gen([1,2], ['a','b','c','d'])]) | |
{1: 'a', 2: 'b'} | |
>>> dict([(a,b) for (a,b) in zip_gen([1,2,3,4], ['a'])]) | |
{1: 'a', 2: None, 3: None, 4: None} | |
''' | |
iter_key = list_key.__iter__() | |
iter_value = list_value.__iter__() | |
while True: | |
try: | |
key = iter_key.next() | |
try: | |
value = iter_value.next() | |
yield(key, value) | |
except StopIteration as vse: | |
yield (key, None) | |
except StopIteration as kse: | |
return | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment