编写一个循环并记住前一个循环是很常见的。
我想要一台为我做这件事的发电机。类似的东西:
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]
答案 0 :(得分:37)
[y - x for x,y in zip(L,L[1:])]
答案 1 :(得分:4)
l = [(0,3), (3,4), (4,10), (10,2), (2,3)]
print [(y-x) for (x,y) in l]
输出:[3,1,6,-8,1]
答案 2 :(得分:4)
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]
[编辑]
此外,这也适用(Python< 3):
>>> map(lambda(a, b):b - a, pairwise(L))