Subtract all items in the list against each other

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 element along with the others, for example:

 (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 will 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 probably save the previous item and check it for the one I'm working with at the moment, but it actually doesn't work.

+6
source share
3 answers

Use itertools.combinations with tuple unpacking to generate difference pairs:

 >>> 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)] 
+12
source

You can use list comprehension, with np.subtract "subtract" 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)] 
+4
source

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)] >>> 
+1
source

All Articles