zip 一次计算所有列表,izip 仅在请求时计算元素。
一个重要的区别是'zip'返回一个实际的列表,'izip'返回一个'izip object',它不是一个列表并且不支持特定于列表的功能(例如索引):
>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [2, 3, 4, 5, 6, 7]
>>> z = zip(l1, l2)
>>> iz = izip(l1, l2)
>>> isinstance(zip(l1, l2), list)
True
>>> isinstance(izip(l1, l2), list)
False
>>> z[::2] #Get odd places
[(1, 2), (3, 4), (5, 6)]
>>> iz[::2] #Same with izip
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'itertools.izip' object is unsubscriptable
所以,如果您需要一个列表(不是类似列表的对象),只需使用 'zip'。
除此之外,“izip”对于节省内存或周期很有用。
例如以下代码可能会在几个周期后退出,因此无需计算组合列表的所有项目:
lst_a = ... #list with very large number of items
lst_b = ... #list with very large number of items
#At each cycle, the next couple is provided
for a, b in izip(lst_a, lst_b):
if a == b:
break
print a
使用zip 会在进入循环之前计算出所有 (a, b) 对。
此外,如果lst_a 和lst_b 非常大(例如数百万条记录),zip(a, b) 将构建第三个带有双倍空格的列表。
但如果您的列表很小,也许zip 更快。