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

遍历Python中相邻元素的“窗口”

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

遍历Python中相邻元素的“窗口”

结果函数(来自问题的编辑),

来自@ agf,@ FogleBird,@ senderle的答案的想法的弗兰肯尼特,其结果看起来有些整洁:

from itertools import chain, repeat, islicedef window(seq, size=2, fill=0, fill_left=True, fill_right=False):    """ Returns a sliding window (of width n) over data from the iterable:      s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...    """    ssize = size - 1    it = chain(      repeat(fill, ssize * fill_left),      iter(seq),      repeat(fill, ssize * fill_right))    result = tuple(islice(it, size))    if len(result) == size:  # `<=` if okay to return seq if len(seq) < size        yield result    for elem in it:        result = result[1:] + (elem,)        yield result

并且,有关一些双端队列/元组的性能信息:

In [32]: kwa = dict(gen=xrange(1000), size=4, fill=-1, fill_left=True, fill_right=True)In [33]: %timeit -n 10000 [a+b+c+d for a,b,c,d in tmpf5.ia(**kwa)]10000 loops, best of 3: 358 us per loopIn [34]: %timeit -n 10000 [a+b+c+d for a,b,c,d in tmpf5.window(**kwa)]10000 loops, best of 3: 368 us per loopIn [36]: %timeit -n 10000 [sum(x) for x in tmpf5.ia(**kwa)]10000 loops, best of 3: 340 us per loopIn [37]: %timeit -n 10000 [sum(x) for x in tmpf5.window(**kwa)]10000 loops, best of 3: 432 us per loop

但是无论如何,如果是数字,那么numpy可能更可取。



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

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

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