简体   繁体   中英

zip in IronPython 2.7 and Python3.5

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 ?

You can use builtins from the future lib.

from builtins import zip

In python2 you get an itertools.izip and in python3 you just get zip.

In [1]: from builtins import zip

In [2]: zip([1,2,3,4])
Out[2]: <itertools.izip at 0x7fa16c8496c8>

In [1]: from builtins import zip

In [2]: zip([1,2,3,4])
Out[2]: <zip at 0x7f13dfb9c188>

That looks perfectly reasonable to me. A small modification will allow you to avoid the explicit version number check by doing

try:
    from itertools import izip as zip_
except ImportError:
    # Python 3
    zip_ = zip

For Python3.5 users,

A=[1,2,3,4,5,6,7]
B=[7,6,5,4,32,1]

In: c=list(zip(A,B))

In: print(c)

out: [(1,7),(2,6),(3,5),(4,4),(5,3),(6,2),(7,1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM