我有一个脚本,我想在Python3.5和IronPython2.7中执行。
该脚本最初是用Python3编写的,所以我有一些类似于下面代码的嵌套循环:
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
现在如果我在IronPython2.7中运行它,我不会得到相同的结果,因为zip返回一个列表而不是迭代器。
为了避免这个问题,我想我会这样做:
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
有没有更好的方法呢?
答案 0 :(得分:3)
from builtins import zip
在python2中,你得到一个itertools.izip
,在python3中你得到一个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>
答案 1 :(得分:2)
这对我来说非常合理。一个小的修改将允许您通过执行
来避免显式版本号检查try:
from itertools import izip as zip_
except ImportError:
# Python 3
zip_ = zip
答案 2 :(得分:-1)
对于Python3.5用户,
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)]