代码之家  ›  专栏  ›  技术社区  ›  Eddy Pronk

减去列表中的当前项和上一项

  •  10
  • Eddy Pronk  · 技术社区  · 14 年前

    写一个循环并记住前面的循环是很常见的。

    import operator
    
    def foo(it):
        it = iter(it)
        f = it.next()
        for s in it:
            yield f, s
            f = s
    

    现在按对减去。

    L = [0, 3, 4, 10, 2, 3]
    
    print list(foo(L))
    print [x[1] - x[0] for x in foo(L)]
    print map(lambda x: -operator.sub(*x), foo(L)) # SAME
    

    输出:

    [(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)]
    [3, 1, 6, -8, 1]
    [3, 1, 6, -8, 1]
    
    • 写这篇文章的更好方法是什么?
    • 有没有一个内置函数可以做类似的事情?
    • 试图使用“map”并没有简化它。怎么办?
    3 回复  |  直到 14 年前
        1
  •  38
  •   jezrael    9 年前
    [y - x for x,y in zip(L,L[1:])]
    
        2
  •  4
  •   Madison Caldwell    14 年前
    l = [(0,3), (3,4), (4,10), (10,2), (2,3)]
    print [(y-x) for (x,y) in l]
    

    输出:[3,1,6,-8,1]

        3
  •  4
  •   pillmuncher    14 年前

    Recipe from iterools

    from itertools import izip, tee
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)
    

    然后:

    >>> L = [0, 3, 4, 10, 2, 3]
    >>> [b - a for a, b in pairwise(L)]
    [3, 1, 6, -8, 1]
    

    [编辑]

    >>> map(lambda(a, b):b - a, pairwise(L))