Hi, I'm having a trouble with new Python 3.7 when use next code, I have got next raise Exception StopIteration, but I have not it when use 2.7.
def _zip(*args):
iters = list(map(iter, args))
while iters:
res = [next(i) for i in iters]
yield tuple(res)
if __name__ == '__main__':
s1, s2 = 'abc', 'xyz123'
print(list(_zip(s1, s2)))
thanks in advance.
I know you made this function as demonstration.
Here an example which works with Python 2.7 and Python 3.7:
from __future__ import print_function
import sys
def _zip1(*args):
iters = list(map(iter, args))
while iters:
res = [next(i) for i in iters]
yield tuple(res)
def _zip2(*args):
for i in zip(*args):
yield tuple(i)
if __name__ == '__main__':
print('Python Version:', sys.version)
s1, s2 = 'abc', 'xyz123'
print('Your example:')
try:
print(list(_zip1(s1, s2)))
except Exception as e:
print(e)
print('Modified version:')
print(list(_zip2(s1, s2)))
Output:
deadeye@nexus ~ $ python w.py
Python Version: 3.7.0 (default, Jun 28 2018, 17:48:59)
[GCC 8.1.1 20180531]
Your example:
generator raised StopIteration
Modified version:
[('a', 'x'), ('b', 'y'), ('c', 'z')]
deadeye@nexus ~ $ python2 w.py
Python Version: 2.7.15 (default, Jun 27 2018, 13:05:28)
[GCC 8.1.1 20180531]
Your example:
[('a', 'x'), ('b', 'y'), ('c', 'z')]
Modified version:
[('a', 'x'), ('b', 'y'), ('c', 'z')]
The modified function is even shorter and easier to understand.
Have a nice weekend.