On 22.04.20 06:43, Soni L. wrote:



On 2020-04-21 7:12 p.m., Steven D'Aprano wrote:
On Tue, Apr 21, 2020 at 05:33:24PM -0300, Soni L. wrote:

> 1. see the other thread (strict zip), especially the parts where they > brought up the lack of peekable/unput iterators in the context of > getting a count out of an iterator.

I've seen it, as far as I can tell there are already good solutions
for getting a count out of an iterator.

are there *any* solutions for getting partial results out of zip with different-length iterators of unknown origin?


You can basically use the code from this StackOverflow answer (code attached below) to cache the last object yielded by each iterator: https://stackoverflow.com/a/61126744

    iterators = [
        iter([0, 1, 2]),
        iter([3, 4]),
        iter([5]),
        iter([6, 7, 8])
    ]

    iterators = [cache_last(i) for i in iterators]
    print(list(zip(*iterators)))   # [(0, 3, 5, 6)]

    partial = []
    for i in iterators:
        try:
            partial.append(i.last)
        except StopIteration:
            break
    print(partial)   # [1, 4]


This is the code for `cache_last`:

    class cache_last:
        def __init__(self, iterable):
            self.obj = iterable
            self._iter = iter(iterable)
            self._sentinel = object()

        @property
        def last(self):
            if self.exhausted:
                raise StopIteration
            return self._last

        @property
        def exhausted(self):
            if not hasattr(self, '_last'):
                raise ValueError('Not started!')
            return self._last is self._sentinel

        def __next__(self):
            try:
                self._last = next(self._iter)
            except StopIteration:
                self._last = self._sentinel
                raise
            return self._last

        def __iter__(self):
            return self

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/37OI7YBIGCW3Y5JD347XWY3RM3I3SJZC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to