[issue30346] Odd behavior when unpacking `itertools.groupby`

Raymond Hettinger report at bugs.python.org
Thu May 11 23:41:44 EDT 2017


Raymond Hettinger added the comment:

FYI, the CPython behavior matches the pure python implementation show in the docs:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        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
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

>>> from operator import itemgetter
>>> inputs = ((x > 5, x) for x in range(10))
>>> (_, a), (_, b) = groupby(inputs, key=itemgetter(0))
>>> print(list(a))
[]
>>> print(list(b))
[(True, 9)]

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30346>
_______________________________________


More information about the Python-bugs-list mailing list