Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract all items in a 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 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.

like image 352
coconut Avatar asked Jan 11 '16 10:01

coconut


People also ask

How do you subtract all the elements in a list?

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.

How do you subtract a list of strings?

Method #1 : Using loop + remove() In this, we perform the removal of elements using remove() and check for similar elements using loop.

How do you subtract values from an array?

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.


3 Answers

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)]
like image 102
Alex Riley Avatar answered Oct 23 '22 17:10

Alex Riley


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)]
like image 36
gtlambert Avatar answered Oct 23 '22 18:10

gtlambert


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)]
>>>
like image 36
styvane Avatar answered Oct 23 '22 17:10

styvane