Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting the current and previous item in a list

Tags:

python

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?
like image 266
Eddy Pronk Avatar asked Oct 27 '10 01:10

Eddy Pronk


People also ask

How do you subtract elements in a list?

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 we subtract two strings in python?

Can you subtract 2 strings in Python? The Python string doesn't have a subtraction operator.

How do you subtract an array in Python?

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.


2 Answers

[y - x for x,y in zip(L,L[1:])]
like image 163
ceth Avatar answered Oct 15 '22 16:10

ceth


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]

like image 26
Madison Caldwell Avatar answered Oct 15 '22 16:10

Madison Caldwell