2016-01-11 26 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)] 
>>> 
相关问题