How to unzip an iterator?

后端 未结 3 664
南方客
南方客 2021-02-19 10:45

Given a list of pairs xys, the Python idiom to unzip it into two lists is:

xs, ys = zip(*xys)

If xys is an iterator,

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 11:03

    The full answer locates here. Long story short: we can modify Python recipe for itertools.tee function like

    from collections import deque
    
    
    def unzip(iterable):
        """
        Transposes given iterable of finite iterables.
        """
        iterator = iter(iterable)
        try:
            first_elements = next(iterator)
        except StopIteration:
            return ()
        queues = [deque([element])
                  for element in first_elements]
    
        def coordinate(queue):
            while True:
                if not queue:
                    try:
                        elements = next(iterator)
                    except StopIteration:
                        return
                    for sub_queue, element in zip(queues, elements):
                        sub_queue.append(element)
                yield queue.popleft()
    
        return tuple(map(coordinate, queues))
    

    and then use it

    >>> from itertools import count
    >>> zipped = zip(count(), count())
    >>> xs, ys = unzip(zipped)
    >>> next(xs)
    0
    

提交回复
热议问题