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-in function that does something similar?
- Trying to use 'map' didn't simplify it. What does?