栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

通过简单地缩短传递到范围的“
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
而不是复制粘贴代码。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470523.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号