zip iterators asserting for equal length in python

前端 未结 5 2335
不思量自难忘°
不思量自难忘° 2020-12-15 18:19

I am looking for a nice way to zip several iterables raising an exception if the lengths of the iterables are not equal.

In the case where the iterables

5条回答
  •  伪装坚强ぢ
    2020-12-15 18:47

    I can think of a simpler solution, use itertools.zip_longest() and raise an exception if the sentinel value used to pad out shorter iterables is present in the tuple produced:

    from itertools import zip_longest
    
    def 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
    

    Unfortunately, we can't use zip() with yield from to avoid a Python-code loop with a test each iteration; once the shortest iterator runs out, zip() would advance all preceding iterators and thus swallow the evidence if there is but one extra item in those.

提交回复
热议问题