将 Python 列表拆分为重叠块的列表

2023-11-23

这个问题类似于将列表切片为子列表列表,但就我而言,我想将每个先前子列表的最后一个元素作为下一个子列表中的第一个元素。我必须考虑到最后一个子列表始终必须至少有两个元素。

例如:

list_ = ['a','b','c','d','e','f','g','h']

大小为 3 的子列表的结果:

resultant_list = [['a','b','c'],['c','d','e'],['e','f','g'],['g','h']]

中的列表理解回答你链接的通过简单地缩短传递给范围的“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']]

这个问题的其他访问者可能没有机会使用输入list(可切片,已知长度,有限)。这是一个基于生成器的解决方案,可以使用任意迭代:

from collections import deque

def 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:]

Note:我已经发布了这个实现wimpy.util.chunks。如果您不介意添加依赖项,您可以pip install wimpy并使用from wimpy import chunks而不是复制粘贴代码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Python 列表拆分为重叠块的列表 的相关文章