Applying a list function to nested generators in itertools.groupby

How does the function work listwhen applied to nested generators? In the following code snippet, I find the behavior rather mysterious: it seems that it listconsumes most of the nested generators, except for the last one, which still saves one element:

>>> from itertools import groupby
>>> xs = [1, 2, 2, 3, 3]
>>> for k, g in list(groupby(xs)):
...     print(k, list(g))
1 []
2 []
3 [3]
+4
source share
1 answer

No, a call to the list will not consume the nested iterator / generator.

The behavior is typical for itertools.groupbyand described in the documents:

, iterable groupby(). , groupby() , .

[ ]

Python itertools.groupby, , :

class groupby(object):
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key

        self.it = iter(iterable) # shared iterator

        self.tgtkey = self.currkey = self.currvalue = object()

    def __iter__(self):
        return self

    def next(self):
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey))

    def _grouper(self, tgtkey):
        while self.currkey == tgtkey:
            yield self.currvalue
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)

[3], , self.currvalue ( _grouper), groupby.

, groupby.

+6

Source: https://habr.com/ru/post/1664324/


All Articles