I have a list in Python that looks like this:
myList = [(1,1),(2,2),(3,3),(4,5)]
And I want to subtract each item with the others, like this:
(1,1) - (2,2)
(1,1) - (3,3)
(1,1) - (4,5)
(2,2) - (3,3)
(2,2) - (4,5)
(3,3) - (4,5)
The expected result would be a list with the answers:
[(1,1), (2,2), (3,4), (1,1), (2,3), (1,2)]
How can I do this? If I approach it with a for
loop, I can maybe store the previous item and check it against the one that I'm working with at that moment, but it doesn't really work.
Use a for-loop to subtract a value from every number in a list. Call range(stop) in a for-loop with stop as the length of the list to iterate over the indices of the list. Subtract the desired value from each number in the list and reassign the difference to the corresponding index.
Method #1 : Using loop + remove() In this, we perform the removal of elements using remove() and check for similar elements using loop.
Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.
Use itertools.combinations
with tuple unpacking to generate the pairs of differences:
>>> from itertools import combinations
>>> [(y1-x1, y2-x2) for (x1, x2), (y1, y2) in combinations(myList, 2)]
[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
You could use a list comprehension, with np.subtract
to 'subtract' the tuples from each other:
import numpy as np
myList = [(1,1),(2,2),(3,3),(4,5)]
answer = [tuple(np.subtract(y, x)) for x in myList for y in myList[myList.index(x)+1:]]
print(answer)
Output
[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
Using operator.sub
with combinations
.
>>> from itertools import combinations
>>> import operator
>>> myList = [(1, 1),(2, 2),(3, 3),(4, 5)]
>>> [(operator.sub(*x), operator.sub(*y)) for x, y in (zip(ys, xs) for xs, ys in combinations(myList, 2))]
[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
>>>
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