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

遍历Python中相邻元素的“窗口”,第1张

遍历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可能更可取。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5666849.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存