python - 写类似 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)
我想知道是否有更好的方法来实现它,以便同时实现这两个目标。
解决方案
推荐阅读
- amazon-web-services - AmazonDynamoDBClient 出错 - getCredentialsProvider() 函数
- c# - 对 File.ReadAllText 方法进行单元测试
- python - 试图在 pygame 中将重力引入类似马里奥的平台游戏中
- javascript - 如何显示从 React 列表中添加的项目数?
- c# - C#通过多级数组仅根据键名查找JSON值
- python - 删除熊猫系列中仅作为标点符号的单词
- java - 为什么在 Netbeans 8.2 中加载我的共享对象文件会出现“不满意的链接”错误?
- python - 为什么这个生成器管道比 Python 中的传统循环慢?
- vim - 如何在 Vim 的每一行末尾的特定列中添加一个字符?
- javascript - 是否可以在不重新加载页面的情况下从输入类型文件中删除文件?