Most pythonic way to get the previous element

后端 未结 5 1845
忘掉有多难
忘掉有多难 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
    
    0 讨论(0)
  • 2021-01-04 19:54

    The best answer I have (and this requires itertools) is

    def offset(iter, n=1):
        # returns tuples (None, iter0), (iter0, iter1), (iter1, iter2) ...
        previous = chain([None] * n, iter)
        return izip(previous, iter)
    

    but I would be interested in seeing if someone has a one-liner (or a better name than offset for this function)!

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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 :).

    0 讨论(0)
  • 2021-01-04 20:10

    To put more itertools on the table:

    from itertools import tee, izip, chain
    
    def tee_zip(iterable):
       a, b = tee(iterable)
       return izip(chain([None], a), b)
    
    0 讨论(0)
提交回复
热议问题