大多数pythonic方式获得前一个元素 [英] Most pythonic way to get the previous element

查看:115
本文介绍了大多数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方式获得前一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆