Most pythonic way to get the previous element

后端 未结 5 1876
忘掉有多难
忘掉有多难 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:01

    def pairwise(iterable):
        """s -> (s0,s1), (s1,s2), (s2, s3), ...
        see http://docs.python.org/library/itertools.html
        """
        a, b = itertools.tee(iterable)
        b.next()
        return itertools.izip(a, b)
    

    EDIT moved doc string into the function

提交回复
热议问题