Most pythonic way to get the previous element

后端 未结 5 1844
忘掉有多难
忘掉有多难 2021-01-04 19:18

I would like an enumerate-like functional on iterators which yields the pair (previous_element, current_element). That is, given that iter

5条回答
  •  时光说笑
    2021-01-04 19:51

    What about the simple (obvious) solution?

    def offset(iterable):
        prev = None
        for elem in iterable:
            yield prev, elem
            prev = elem
    

提交回复
热议问题