请看下面由我编写的函数
zzip()
,它将实现您想要的功能。它使用了
itertools
模块中的
zip_longest
方法,并返回一个元组,其中包括
zip
返回的内容以及一个索引列表,如果不为空,则显示在哪个基于0的位置上迭代器/可迭代对象耗尽了,而其他迭代器/可迭代对象没有耗尽:
def zzip(*args):
""" Returns a tuple with the result of zip(*args) as list and a list
with ZERO-based indices of iterables passed to zzip which got
exhausted before other ones. """
from itertools import zip_longest
nanNANaN = 'nanNANaN'
Zipped = list(zip_longest(*args, fillvalue=nanNANaN))
ZippedT = list(zip(*Zipped))
Indx_exhausted = []
indx_nanNANaN = None
for i in range(len(args)):
try:
indx_nanNANaN = ZippedT[i].index(nanNANaN)
Indx_exhausted += [(indx_nanNANaN, i)]
except ValueError:
pass
if Indx_exhausted:
Indx_exhausted.sort()
min_indx_nanNANaN = Indx_exhausted[0][0]
Indx_exhausted = [
i for n, i in Indx_exhausted if n == min_indx_nanNANaN ]
return (Zipped[:min_indx_nanNANaN], Indx_exhausted)
else:
return (Zipped, Indx_exhausted)
assert zzip(iter([1,2,3]),[4,5],iter([6])) ==([(1,4,6)],[2])
assert zzip(iter([1,2]),[3,4,5],iter([6,7]))==([(1,3,6),(2,4,7)],[0,2])
assert zzip([1,2],[3,4],[5,6]) ==([(1,3,5),(2,4,6)],[])
上述代码在使用的测试用例中没有引发断言错误。
请注意,函数中的“for循环”循环遍历传递的参数列表的项目,而不是传递的可迭代元素。
itertools.zip_longest
而不是zip
。 - wjandreaa
并在循环内获取next(b)
,但我不确定如果a
较短是否完全相同。 - Kraken