Most pythonic way to get the previous element

后端 未结 5 1846
忘掉有多难
忘掉有多难 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 20:09

    def offset(iter, n=1, pad=None):
        i1, i2 = itertools.tee(iter)
        i1_padded = itertools.chain(itertools.repeat(pad, n), i1)
        return itertools.izip(i1_padded, i2)
    

    @bpgergo + @user792036 = this. Best of two worlds :).

提交回复
热议问题