我可以想到一个更简单的解决方案,
itertools.zip_longest()如果产生的元组中存在用于填充较短的可迭代对象的哨兵值,请使用并引发异常:
from itertools import zip_longestdef zip_equal(*iterables): sentinel = object() for combo in zip_longest(*iterables, fillvalue=sentinel): if sentinel in combo: raise ValueError('Iterables have different lengths') yield combo不幸的是,我们不能使用
zip()with
yieldfrom来避免每次迭代都进行测试的Python代码循环。一旦最短的迭代器用完,
zip()将推进所有先前的迭代器,从而吞噬证据,如果其中仅包含一个额外的项目。



