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

这更多是关于优雅和性能的问题,而不是“根本如何做”,因此我将仅显示代码:

def iterate_adjacencies(gen, fill=0, size=2, do_fill_left=True,

do_fill_right=False):

""" Iterates over a 'window' of `size` adjacent elements in the supploed

`gen` generator, using `fill` to fill edge if `do_fill_left` is True

(default), and fill the right edge (i.e. last element and `size-1` of

`fill` elements as the last item) if `do_fill_right` is True. """

fill_size = size - 1

prev = [fill] * fill_size

i = 1

for item in gen: # iterate over the supplied `whatever`.

if not do_fill_left and i < size:

i += 1

else:

yield prev + [item]

prev = prev[1:] + [item]

if do_fill_right:

for i in range(fill_size):

yield prev + [fill]

prev = prev[1:] + [fill]

然后问:该功能已经存在吗?而且,如果没有,您能否以更好的方式(例如,更简洁和/或更快速)来做相同的事情?

编辑:

从@ agf,@ FogleBird,@ senderle的答案中得到的想法,最终的代码看起来很整洁:

def 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值