通过简单地缩短传递到范围的“
step”参数,可以轻松地将链接的答案中的列表理解用于支持重叠的块:
>>> list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']>>> n = 3 # group size>>> m = 1 # overlap size>>> [list_[i:i+n] for i in range(0, len(list_), n-m)][['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h']]
这个问题的其他访问者可能没有足够的精力来处理输入 列表 (可分割,已知长度,有限)。这是一个基于生成器的解决方案,可以与任意可迭代对象一起使用:
from collections import dequedef chunks(iterable, chunk_size=3, overlap=0): # we'll use a deque to hold the values because it automatically # discards any extraneous elements if it grows too large if chunk_size < 1: raise Exception("chunk size too small") if overlap >= chunk_size: raise Exception("overlap too large") queue = deque(maxlen=chunk_size) it = iter(iterable) i = 0 try: # start by filling the queue with the first group for i in range(chunk_size): queue.append(next(it)) while True: yield tuple(queue) # after yielding a chunk, get enough elements for the next chunk for i in range(chunk_size - overlap): queue.append(next(it)) except StopIteration: # if the iterator is exhausted, yield any remaining elements i += overlap if i > 0: yield tuple(queue)[-i:]
注意:
此后,我已经在中发布了此实现
wimpy.util.chunks。如果您不介意添加依赖项,则可以
pipinstall wimpy并且可以使用
from wimpy import chunks而不是复制粘贴代码。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)