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]
To perform list subtraction, the two input lists must be of the same length and it should contain elements of the same type i.e. both lists must contain only numerical values. The given example subtracts the elements at each index in one list from the other list.
Can you subtract 2 strings in Python? The Python string doesn't have a subtraction operator.
subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.
[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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With