I have a script that I want to execute both in Python3.5 and IronPython2.7.
The script is originally written with Python3 in mind, so I have some nested loops similar to the code below :
myIter0 = iter(['foo','foo','bar','foo','spam','spam'])
myIter1 = iter(['foo','bar','spam','foo','spam','bar'])
myIter2 = iter([1,2,3,4,5,6])
for a in myIter0:
for b, c in zip(myIter1, myIter2):
if a + b == 'foobar':
print(c)
break
Now if I run this in IronPython2.7 I don't get the same result because zip returns a list and not an iterator.
To circumvent this problem, I thought I would do :
import sys
if sys.version_info.major == 2:
from itertools import izip as _zip
else:
_zip = zip
myIter0 = iter(['foo','foo','bar','foo','spam','spam'])
myIter1 = iter(['foo','bar','spam','foo','spam','bar'])
myIter2 = iter([1,2,3,4,5,6])
for a in myIter0:
for b, c in _zip(myIter1, myIter2):
if a + b == 'foobar':
print(c)
break
Is there any better way to do this ?
zip
returning a list in python2? Or is it specific to IronPython? – Lolitazip(myIter1, myIter2)
uses all the items inmyIter1
andmyIter2
in Python2. The program doesn't reenter the nestedfor
loop sincezip(myIter1, myIter2)
is an empty iterator after the first iteration of the main loop. – Overlaysix.zip()
? – Lunatesix
though. – Overlay