开发者

Subtracting the current and previous item in a list

It is very common to write a loop and remember the previous.

I want a generator that does that for me. Something like:

import operator

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

Now subtract pair-wise.

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

Outputs:

[(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)]
[3, 1, 6, -8, 1]
[3, 1, 6, -8, 1]
  • What is a good name for this operation?
  • What is a better way to write this?
  • Is there a built-开发者_JAVA技巧in function that does something similar?
  • Trying to use 'map' didn't simplify it. What does?


[y - x for x,y in zip(L,L[1:])]


l = [(0,3), (3,4), (4,10), (10,2), (2,3)]
print [(y-x) for (x,y) in l]

Outputs: [3, 1, 6, -8, 1]


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)

and then:

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

[EDIT]

Also, this works (Python < 3):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜