首页 > 解决方案 > 写类似 groupby 的更好方法?

问题描述

我知道 itertools 中有一个 groupby 可迭代对象,出于好奇,我开始编写自己的实现。

我关心的两个标准是可读性(并且是 pythonic)其次是效率(例如,不要重复序列两次)。

我想出了两个实现,一个满足前一个标准,第二个满足后者:

def my_groupby(container):
    for idx, target_key in enumerate(container):
        if idx > 0 and target_key == container[idx - 1]:
            continue
        yield (curr_key for curr_key in takewhile(lambda key: key == target_key, container[idx:]))


class my_groupby2:
    class _my_group:
        def __init__(self, parent):
            self._parent = parent

        def __iter__(self):
            return self

        def __next__(self):
            if self._parent._curr_idx == self._parent._container_len:
                raise StopIteration
            curr_key = self._parent._container[self._parent._curr_idx]
            if curr_key != self._parent._target_key:
                self._parent._target_key = curr_key
                raise StopIteration
            self._parent._curr_idx += 1
            return curr_key

    def __init__(self, container):
        self._container = container
        self._target_key = container[0]
        self._container_len = len(container)
        self._curr_idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._curr_idx == self._container_len:
            raise StopIteration
        return self._my_group(self)

我想知道是否有更好的方法来实现它,以便同时实现这两个目标。

标签: python

解决方案


推荐阅读