本文介绍了大多数pythonic方式获得前一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在迭代器上有一个枚举
-like函数,它产生对(previous_element,current_element)
。也就是说,假设 iter
是
I would like an enumerate
-like functional on iterators which yields the pair (previous_element, current_element)
. That is, given that iter
is
i0, i1, i1, ...
我想要抵消(iter)
收益
(None, i0), (i0, i1), (i1, i2) ...
推荐答案
简单(明显)解决方案怎么样?
What about the simple (obvious) solution?
def offset(iterable):
prev = None
for elem in iterable:
yield prev, elem
prev = elem
这篇关于大多数pythonic方式获得前一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!