I have a list of tuples
lst = [(1,2,3),(1,2,3),(7,8,9)]
And
I want to find the difference between previous tuple from the next like this:
ans = [(0,0,0), (6,6,6)]
How can I do this in Python?
CodePudding user response:
from functools import reduce, partial
from operator import sub
my_list = [(1,2,3),(1,2,3),(7,8,9)]
diff_list = list(map(partial(reduce, lambda a, b: tuple(map(sub, a, b))), zip(my_list[1:], my_list)))
To break it down:
zip(my_list[1:], my_list)
This creates a new iterator which yields iterables consisting of every next element of the list followed by the previous.
partial(reduce, lambda a, b: tuple(map(sub, a, b)))
This creates a function which when given an iterable whose elements consist of tuples, will return a new tuple containing the difference between the first and the second tuples. It could be more tuples, but in our case, we only ever pass to this function an iterable consisting of two tuples, it will always do what we want.
CodePudding user response:
Try:
lst = [(1, 2, 3), (1, 2, 3), (7, 8, 9)]
out = [tuple(b - a for a, b in zip(t1, t2)) for t1, t2 in zip(lst, lst[1:])]
print(out)
Prints:
[(0, 0, 0), (6, 6, 6)]
CodePudding user response:
You can iterate over the data and use the sub
method from the operator package to subtract the tuples:
from operator import sub
data = [(1,2,3),(1,2,3),(7,8,9)]
diff = [tuple(map(sub, data[i 1], data[i])) for i in range(0, len(data)-1)]
You could also use a for loop instead of the list comprehension if you prefer. The tuple subtraction is from here: Elegant way to perform tuple arithmetic