zip iterators asserting for equal length in python

前端 未结 5 2328
不思量自难忘°
不思量自难忘° 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 19:05

    I came up with a solution using sentinel iterable FYI:

    class _SentinelException(Exception):
        def __iter__(self):
            raise _SentinelException
    
    
    def zip_equal(iterable1, iterable2):
        i1 = iter(itertools.chain(iterable1, _SentinelException()))
        i2 = iter(iterable2)
        try:
            while True:
                yield (next(i1), next(i2))
        except _SentinelException:  # i1 reaches end
            try:
                next(i2)  # check whether i2 reaches end
            except StopIteration:
                pass
            else:
                raise ValueError('the second iterable is longer than the first one')
        except StopIteration: # i2 reaches end, as next(i1) has already been called, i1's length is bigger than i2
            raise ValueError('the first iterable is longger the second one.')
    

提交回复
热议问题