2016-01-11 49 views
6

我有一個Python列表,看起來像這樣:減去列表中的所有項目相互

myList = [(1,1),(2,2),(3,3),(4,5)] 

我想減去各個項目與其他人,像這樣的:

(1,1) - (2,2) 
(1,1) - (3,3) 
(1,1) - (4,5) 
(2,2) - (3,3) 
(2,2) - (4,5) 
(3,3) - (4,5) 

預期結果將與答案列表:

[(1,1), (2,2), (3,4), (1,1), (2,3), (1,2)] 

我該怎麼做?如果我用for循環來處理它,我可以存儲前一個項目,並檢查它是否與我當時正在使用的項目相對應,但它不起作用。

+0

什麼是'(1,1) - (2,2)'? '(-1,-1)'還是別的? –

+0

@BoristheSpider,是,(-1,-1)或(1,1)。要麼,我不關心標誌。 – coconut

回答

12

使用itertools.combinations與元組拆包,以產生對差異:

>>> 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)] 
4

你可以使用一個列表的理解,與np.subtract互相「減」的元組:

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) 

輸出

[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)] 
1

使用operator.subcombinations

>>> 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)] 
>>> 
相關問題